标签:
leetcode - Best Time to Buy and Sell Stock III
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.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size() == 0) return 0; vector<int> pricesForward(prices.size(),0), pricesBackward(prices.size(),0); int low = prices[0], maxPrice = 0; for(int i = 1; i < prices.size(); i++){ if(low > prices[i]){ low = prices[i]; } else if(maxPrice < prices[i] - low){ maxPrice = prices[i] - low; } pricesForward[i] = maxPrice; } int high = prices[prices.size()-1]; maxPrice = 0; for(int i = prices.size()-2; i >= 0; i--){ if(high < prices[i]){ high = prices[i]; } else if(maxPrice < high - prices[i]){ maxPrice = high - prices[i]; } pricesBackward[i] = maxPrice; } int ans = 0; for(int i = 0; i < prices.size(); i++){ if(pricesForward[i]+pricesBackward[i] > ans) ans = pricesForward[i]+pricesBackward[i]; } return ans; } };
自己开始的想法是错的,以为可以仿照前面的题求出最大的两个利润。结果发现显然是错的,因为这两个最大值可能是在重叠的序列上产生的。
看了网上的解答,都是考虑将序列分成两段,分别计算这两段的最大利润,然后找到最大的组合。但是如果对每一个分界点的前后两个序列每次都计算最大利润的话会TLE,
所以可以使用动态规划来做,分前向遍历和后向遍历。对于前向遍历,方法和之前的一样,要保存从0-i所能获得的最大利润,
后续遍历类似于前向遍历,但是不同之处在于,是找最大值(前向的时候是找最小值),并计算最大值与所遍历的元素的差。
例如:序列: 2 1 2 0 1
前向遍历: 0 0 1 1 1
后向遍历: 1 1 1 1 0
组合: 1 1 2 2 1
最大值为2.
参考:
http://blog.csdn.net/jellyyin/article/details/8671277
http://www.cnblogs.com/lihaozy/archive/2012/12/19/2825525.html
http://www.tuicool.com/articles/NnAnYz
http://www.tuicool.com/articles/rMJZj2
leetcode - Best Time to Buy and Sell Stock III
标签:
原文地址:http://www.cnblogs.com/shnj/p/4742799.html