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).
Solution: we divide the whole sequence into two parts at each i, find the maximum intervals or profits in both left and right parts, add both of them together to get the maximum profit on this division. Then we select the largest one. We employ DP to solve this problem [another good explanation can be found here].
class Solution { public: int maxProfit(vector<int> &prices) { // Start typing your C/C++ solution below // DO NOT write int main() function if(prices.empty()) return 0; int n = prices.size(); //compute the max profit until right now vector<int> historyProfit(n, 0); int curMin = prices[0]; for(int i=1; i<n; i++){ curMin = min(curMin, prices[i]); historyProfit[i] = max(historyProfit[i-1], prices[i]-curMin); } //compute the max profit from now on vector<int> futureProfit(n, 0); int curMax = prices[n-1]; for(int i=n-2; i>=0; i--){ curMax = max(curMax, prices[i]); futureProfit[i] = max(futureProfit[i+1], curMax-prices[i]); } //select the maximum overall profit int maxProfit = 0; for(int i=0; i<n; i++) maxProfit = max(maxProfit, historyProfit[i]+futureProfit[i]); return maxProfit; } };
No comments:
Post a Comment