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 sell the stock before you buy again).
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(!prices.size())return 0;
int *maxl = new int[prices.size() + 1];
int *maxr = new int[prices.size() + 1];
maxl[0] = maxr[prices.size() - 1] = 0;
int mini = prices[0];int m = 0;
for(int i = 1; i < prices.size(); i++)
{
m = max(m,prices[i] - mini);
maxl[i] = m;
mini = min(mini, prices[i]);
}
int maxm = prices[prices.size() - 1];m = 0;
for(int i = prices.size() - 2; i >= 0; i--)
{
m = (m, maxm > prices[i] ? maxm - prices[i] : 0);
maxr[i] = m;
maxm = max(maxm, prices[i]);
}
int rst = maxr[0];
for(int i = 0; i < prices.size() - 1; i++)
{
rst = max(rst, maxl[i] + maxr[i + 1]);
}
return rst;
}
};