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).
思路:
现在让我们来看看Best Time to Buy and Sell Stock这个系列的第三道题。题目中说最多可以买卖两次。所以,解决方法是进行两次DP,两次以当前的第i
天为分界线。第一次是从前往后遍历,如果在第i
天之前发生了一次交易,那么最大profit
就通过跟121. Best Time to Buy and Sell Stock一样的方法,用minPrice
和vector<int>maxProfit1
来分别保存截至目前的最低价格,和截止每一天的最高收益这个数组。第二次是从后往前遍历,假设在第i天以后发生了一次交易,那么我们用maxPrice
来保存今天的价格和过去的最高价格之间更高的那一个,然后用maxProfit2
来保存maxPrice - prices[i]
和当前maxProfit2
中更大的那一个。同时在第二次遍历的时候鼠标求对每一个i
的maxProfit1 + maxProfit2
中的最大值,就是最后需要的结果了。
代码如下:
class Solution {
public:
int maxProfit(vector& prices) {
if(prices.empty()) return 0;
vector<int> maxProfit1(prices.size(), 0);
int minPrice = INT_MAX;
int maxPrice = INT_MIN;
int maxProfit2 = 0;
int res = 0;
for(int i = 0; i < prices.size(); ++i){
minPrice = min(minPrice, prices[i]);
maxProfit1[i] = max(maxProfit1[i - 1], prices[i] - minPrice);
}
for(int i = prices.size() - 1; i >= 0; --i){
maxPrice = max(maxPrice, prices[i]);
maxProfit2 = max(maxPrice - prices[i], maxProfit2);
res = max(res, maxProfit1[i] + maxProfit2);
}
return res;
}
};