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 most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must encrypt the stock before you buy again ).
Idea: Use the idea of Dynamic Planning: traverse the array from front to back and from back to back, respectively, find the maximum profits in the range a [0]-A [I] And a [I]-A [n. Then, traverse the array again to find out the first part of the profit and the next part of the profit plus the maximum profit value. The time complexity is O (n ).
1 class Solution { 2 public: 3 int maxProfit( vector<int> &prices ) { 4 int size = prices.size(); 5 if( size <= 1 ) { return 0; } 6 vector<int> invMaxProfit( size, 0 ); 7 int curMax = prices[size-1]; 8 for( int i = size-2; i >= 0; --i ) { 9 if( curMax <= prices[i] ) {10 curMax = prices[i];11 } else {12 invMaxProfit[i] = curMax - prices[i];13 }14 }15 int curMin = prices[0], profit = 0, totalProfit = invMaxProfit[0];16 for( int i = 0; i < size-1; ++i ) {17 if( curMin > prices[i] ) { curMin = prices[i]; }18 if( profit < prices[i] - curMin ) { profit = prices[i] - curMin; }19 if( totalProfit < profit + invMaxProfit[i+1] ) { totalProfit = profit + invMaxProfit[i+1]; }20 }21 return totalProfit;22 }23 };