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 encrypt the stock before you buy again ).
It should be noted that you can operate twice, but the second purchase can only be performed after the first sale. Therefore, the idea is to use the greedy algorithm to calculate the maximum possible benefits of buying and selling each day, and record the results in an array. Calculate the maximum possible benefits of buying and selling each day in reverse order, and record the results in an array. Then, the sum of the benefits that can be achieved in the two situations corresponding to each day in the two arrays is obtained, and the maximum value is the maximum benefit that can be achieved. The Code is as follows:
class Solution {public: int maxProfit(vector<int> &prices) { if(prices.empty()) return 0; int n = prices.size(); vector<int> pre(n,0); vector<int> post(n,0); int curMin = prices[0]; int curMax = prices[n-1]; int result=0; for(int i=1; i<n; i++) { curMin = curMin<prices[i] ? curMin : prices[i]; int diff = prices[i]-curMin; pre[i] = pre[i-1]>diff ? pre[i-1] : diff; } for(int i=n-2; i>=0; i--) { curMax = curMax>prices[i] ? curMax : prices[i]; int diff = curMax-prices[i]; post[i] = post[i+1]>diff ? post[i+1] : diff; } for(int i=1; i<n; i++) { result = result>(pre[i]+post[i]) ? result : (pre[i]+post[i]); } return result; }};