Leetcode-best time to buy and stock Stock III
Say you have an array for whichITh element is the price of a given stock on dayI.
Design an algorithm to find the maximum profit. You may complete at mostTwoTransactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must encrypt 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; }};
I started thinking wrong, thinking that I could follow the previous question to find the maximum two profits. The result shows that it is obviously wrong, because the two maximum values may be generated on the overlapping sequence.
After reading the answers on the internet, I considered dividing the sequence into two sections, calculating the maximum profits of the two sections, and then finding the largest combination. However, if we calculate the maximum profit for the first and second sequences of each demarcation point, it will be TLE,
Therefore, you can use dynamic planning to split forward traversal and backward traversal. For forward traversal, the method is the same as the previous one, and the maximum profit obtained from 0-i must be saved,
Subsequent traversal is similar to forward traversal, but the difference is that it is to find the maximum value (when the forward direction is to find the minimum value), and calculate the difference between the maximum value and the element to be traversed.
Example: sequence: 2 1 2 0 1
Forward traversal: 0 0 1 1 1
Backward traversal: 1 1 1 1 0
Combination: 1 1 2 2 1
The maximum value is 2.
Refer:
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 stock Stock III