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).
Solution: DP, caculate max profit both forward and backward, then return the max sum of them.
int maxProfit(vector<int> &prices) {
if(prices.size() <= )
return ; vector<int> max_forward;
int lowest = prices[];
int max_profit = ;
max_forward.push_back();
for(int i = ; i < prices.size(); i ++ ){
int profit = prices[i] - lowest;
if(profit > max_profit)
max_profit = profit; max_forward.push_back(max_profit);
lowest = min(prices[i], lowest);
} int result = max_forward[max_forward.size() - ];
vector<int> max_backward;
int largest = prices[prices.size() - ];
max_profit = ;
for(int i = prices.size() - ; i >= ; i --) {
int profit = largest - prices[i];
max_profit = max(profit, max_profit); result = max(result, max_profit + max_forward[i]); largest = max(largest, prices[i]);
}
return result;
}