Given an array, which i-th element is the price of a given stock i-th day.
Design an algorithm to compute the maximum profit you can get. You can complete up to two transactions.
Note: You can not simultaneously involved in multiple transactions (you must sell before buying shares again before the fall).
Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size=prices.size();
if(size==0)
return 0;
vector<int>min1(size,prices[0]),min2(size,prices[0]);
vector<int>max1(size,0),max2(size,0);
for(int i=1;i<size;i++){
min1[i]=min(min1[i-1],prices[i]);
max1[i]=max(max1[i-1],prices[i]-min1[i-1]);
min2[i]=min(min2[i-1],prices[i]-max1[i-1]);
max2[i]=max(max2[i-1],prices[i]-min2[i-1]);
}
return max2[size-1];
}
};