问题描述:
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 twotransactions.
Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).
Example 1:
Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
源码:
想了半天没想到思路,我太菜了,看了看网上的博客,翻出了一个答案。
定义local[i][j]为在到达第i天时最多可进行j次交易并且最后一次交易在最后一天卖出的最大利润,此为局部最优。然后我们定义global[i][j]为在到达第i天时最多可进行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])
其中局部最优值是比较前一天并少交易一次的全局最优加上大于0的差值,和前一天的局部最优加上差值中取较大值,而全局最优比较局部最优和前一天的全局最优
效率很低,时间只有10%,空间14%。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n<2) return 0;
vector<vector<int>> local(n, vector<int>(3, 0)), global(n, vector<int>(3, 0));
for(int i=1; i<n; 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(0, diff), local[i-1][j]+diff);
global[i][j] = max(local[i][j], global[i-1][j]);
}
}
return global[n-1][2];
}
};
换成一维之后就好了很多,之前有意的避免一维的方式,因为太难理解了,结果遇到了这几次,以后需要考虑了。
每次意外循环,相当于求出了global[i][j]和local[i][j]。注意内循环从后向前遍历,因为需要用到上一次的[i-1]
时间97%,空间100%。
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if(n<2) return 0;
vector<int> local(3, 0), global(3, 0);
for(int i=0; i<n-1; i++){
int diff = prices[i+1] - prices[i];
for(int j=2; j>=1; j--){
local[j] = max(global[j-1]+max(diff, 0), local[j]+diff);
global[j] = max(global[j], local[j]);
}
}
return global[2];
}
};