Idea: Add two of the largest profit, the maximum profit of a period is not necessarily only in one rise period, for example, there are two ascending intervals between the Green Line
As long as the maximum profit before I is calculated and the maximum profit after I is added, because I cannot be a peak or a valley value at the same time, it is guaranteed not to buy and sell on the same day
The Green Line profit plus the red line profit is the biggest profit.
Class Solution {//calculates the maximum profit of two segment//calculates the maximum profit before I and the maximum profit after I//l[]: Maximum profit before I//r[]: I after maximum profit//minval:i minimum value Maxval:i after the maximum value Public:int maxprofit (vector<int> &prices) {if (Prices.empty ()) return 0; const int size = Prices.size (); int l[size], r[size], Minval (Prices[0]), Maxval (prices[size-1]); Calculate the maximum profit before I l[0] = 0; for (int i = 1; i < size; I + +) {L[i] = max (l[i-1], prices[i]-minval); minval = min (prices[i], minval); }//Calculate the maximum profit after I r[size-1] = 0; for (int i = size-2; I >= 0; I-) {r[i] = max (r[i+1], maxval-prices[i]); Maxval = Max (Maxval, prices[i]); }//Calculates the total maximum profit int profit (0); for (int i = 0; i < size; I + +) {Profit = max (Profit, L[i] + r[i]); } return profit; }};
Leetcode--best time to Buy and Sell Stock III