题目链接:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/#/description
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
Find the maximum profit you can achieve. 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).
思路1:
这道题是 Best Time to Buy and Sell Stock 的扩展,现在我们最多可以进行两次交易。这里仍然使用动态规划来完成,事实上可以解决非常通用的情况,也就是最多进行k次交易的情况。
这里先解释最多可以进行k次交易的算法,然后最多进行两次我们只需要把k取成2即可。我们还是使用“局部最优和全局最优解法”。我们维护两种量,一个是当前到达第i天可以最多进行j次交易,最好的利润是多少(global[i][j]);另一个是当前到达第i天可以最多进行j次交易,并且最后一次交易在当天时最好的利润是多少(local[i][j])。下面我们来看递推式,全局变量的维护,递推式是
global[i][j] = max(local[i][j],global[i - 1][j]),
也就是取当前局部最好的(local[i][j]),和过往全局最好的那个(global[i-1][j])。因为最后一次交易如果包含当前天一定在局部最好的里面,否则一定在过往全局最优的里面。对于局部变量的维护,递推式是
local[i][j] = max(global[i - 1][j - 1] + max(diff,0),local[i - 1][j] + diff),
也就是看两个量,第一个是全局到i-1天进行j-1次交易,然后加上今天的交易,如果今天是赚钱的话(也就是前面只要j-1次交易,最后一次交易取当前天),第二个量则是取local第i-1天j次交易,然后加上今天的差值(这里因为local[i-1][j]比如包含第i-1天卖出的交易,所以现在变成第i天卖出,并不会增加交易次数,而且这里无论diff是不是大于0都一定要加上,因为否则就不满足local[i][j]必须在最后一天卖出的条件了)。
上面的算法中对于天数需要一次扫描,而每次要对交易次数进行递推式求解,所以时间复杂度是O(n*k),如果是最多进行两次交易,那么复杂度还是O(n)。空间上只需要维护当天数据皆可以,所以是O(k),当k=2,则是O(1)。代码如下:
int maxProfit(vector<int>& prices) {
if(prices.empty())
return 0;
int n = prices.size();
vector<vector<int>> global(n, vector<int>(3, 0));
vector<vector<int>> local(n, vector<int>(3, 0));
for(int i = 1; i < prices.size(); i++) {
int diff = prices[i] - prices[i - 1];
for(int j = 1; j <= 2; j++) {
local[i][j] = max(global[i - 1][j - 1] + max(diff, 0), local[i - 1][j] + diff);
global[i][j] = max(local[i][j], global[i - 1][j]);
}
}
return global[n - 1][2];
}
思路2:
First assume that we have no money, so buy1 means that we have to borrow money from others, we want to borrow less so that we have to make our balance as max as we can(because this is negative).
sell1 means we decide to sell the stock, after selling it we have price[i] money and we have to give back the money we owed, so we have price[i] - |buy1| = prices[i ] + buy1, we want to make this max.
buy2 means we want to buy another stock, we already have sell1 money, so after buying stock2 we have buy2 = sell1 - price[i] money left, we want more money left, so we make it max
sell2 means we want to sell stock2, we can have price[i] money after selling it, and we have buy2 money left before, so sell2 = buy2 + prices[i], we make this max.
So sell2 is the most money we can have.
Hope it is helpful and welcome quesions!
class Solution {
public:
int maxProfit(vector<int>& prices) {
int sell1 = 0, sell2 = 0, buy1 = INT32_MIN, buy2 = INT32_MIN;
for (int i = 0; i < prices.size(); i++) {
buy1 = max(buy1, -prices[i]);
sell1 = max(sell1, buy1 + prices[i]);
buy2 = max(buy2, sell1 - prices[i]);
sell2 = max(sell2, buy2 + prices[i]);
}
return sell2;
}
};