LeetCode - 123. Best Time to Buy and Sell Stock III

 

Description

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Solution

动态规划法:用两个数组,数组f1[i]表示在[0, i]范围内进行一次买入卖出的最大收益,数组f2[i]表示在[i, n-1]范围内进行一次买入卖出的最大收益,则总的最大收益为max(f1[i]+f2[i]),数组f1、f2的求法参考题目121

python

 1 class Solution(object):
 2     def maxProfit(self, prices):
 3         """
 4         :type prices: List[int]
 5         :rtype: int
 6         """
 7         length = len(prices)
 8         if length <= 1:
 9             return 0
10 
11         f1 = []
12         f2 = []
13         min_price = prices[0]
14         f1.append(0)
15         for i in range(1, length):
16             min_price = min(min_price, prices[i])
17             f1.append(max(f1[i-1], prices[i]-min_price))
18 
19         # reverse the prices list to iterate them from behind
20         prices_re = prices
21         prices_re.reverse()
22         f2.append(0)
23         max_price = prices_re[0]
24         for i in range(1, length):
25             max_price = max(max_price, prices_re[i])
26             f2.append(max(f2[i-1], max_price-prices_re[i]))
27 
28         f2.reverse()
29         max_profit = 0
30         for i in range(length):
31             max_profit = max(max_profit, f1[i]+f2[i])
32 
33         return max_profit
View Code

cpp

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         int length = prices.size();
 5         if (length <= 1)
 6             return 0;
 7 
 8         vector<int> f1(length);
 9         vector<int> f2(length);
10         f1[0] = 0;
11         int min_price = prices[0];
12         // get max_profit1 using positive sequence
13         for (int i=1; i<length; ++i)
14         {
15             min_price = min(min_price, prices[i]);
16             f1[i] = max(f1[i-1], prices[i]-min_price);
17         }
18 
19         // get max_profit2 using inverted sequence
20         f2[length-1] = 0;
21         int max_price = prices[length-1];
22         for (int i=length-2; i>=0; --i)
23         {
24             max_price = max(max_price, prices[i]);
25             f2[i] = max(f2[i+1], max_price-prices[i]);
26         }
27 
28         // generate max_profit for output
29         int max_profit = 0;
30         for (int i=0; i<length; ++i)
31         {
32             max_profit = max(max_profit, f1[i]+f2[i]);
33         }
34 
35         return max_profit;
36     }
37 };
View Code

Reference

posted @ 2017-03-31 22:15  朝研行歌  阅读(170)  评论(0编辑  收藏  举报