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]
说明:版权所有,转载请注明出处。 Coder007的博客class Solution {
public:
int maxProfit(vector<int> &prices) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
// empty array
if(prices.size() == 0){
return 0;
}
// variables definition
int left[prices.size()];
int right[prices.size()];
int minPrice = prices[0], maxPrice = prices[prices.size()-1];
// update left
int profit = 0;
for(int i = 0; i < prices.size(); ++i){
left[i] = prices[i] - minPrice;
if(left[i] > profit){
profit = left[i];
}
else{
left[i] = profit;
}
minPrice = min(minPrice, prices[i]);
}
// update right
profit = 0;
for(int i = prices.size()-1; i >= 0; --i){
right[i] = maxPrice - prices[i];
if(right[i] > profit){
profit = right[i];
}
else{
right[i] = profit;
}
maxPrice = max(maxPrice, prices[i]);
}
// get the max profit
int res = 0;
for(int i = 0; i <= prices.size(); ++i){
profit = 0;
if(i-1 >= 0 && i-1 < prices.size()){
profit += left[i-1];
}
if(i < prices.size()){
profit += right[i];
}
res = max(res, profit);
}
return res;
}
};