Best Time to Buy and Sell Stock III:
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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n=prices.size();
vector<int> before(n,0);
int bp=INT_MAX;
int profit=0;
for(int i=0;i<n;i++)
{
if ( prices[i]>bp )
profit=max(profit,prices[i]-bp);
else
bp=prices[i];
before[i]=profit;
}
int maxProfit=profit;
bp=INT_MIN;
profit=0;
for(int i=n-1;i>=0;i--)
{
if ( prices[i] < bp )
profit=max(profit,bp-prices[i]);
else
bp=prices[i];
if ( i>0 )
maxProfit=max(maxProfit,profit+before[i-1]);
}
return maxProfit;
}
};