Best Time to Buy and Sell Stock III(from leetcode
题意:
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) {
int buy1 = -10000;
int buy2 = -10000;
int sell1 = 0;
int sell2 = 0;
for(int i = 0;i<prices.size();i++){
sell2 = max(sell2,buy2+prices[i]);
buy2 = max(buy2,sell1-prices[i]);
sell1 = max(sell1,buy1+prices[i]);
buy1 = max(buy1,-prices[i]);
}
return sell2;
}
};