原题地址:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iv/description/
题目描述:
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 k 笔交易。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: [2,4,1], k = 2
输出: 2
解释: 在第 1 天 (股票价格 = 2) 的时候买入,在第 2 天 (股票价格 = 4) 的时候卖出,这笔交易所能获得利润 = 4-2 = 2 。
示例 2:
输入: [3,2,6,5,0,3], k = 2
输出: 7
解释: 在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4 。
随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。
解题方案:
动态规划,参考博客 https://blog.csdn.net/danielrichard/article/details/75091410
规划方程:
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
const int len = prices.size();
if (len <= 1 || k == 0)
return 0;
if (k > len / 2)
k = len / 2;
const int count = k;
int buy[count];
int sell[count];
for (int i = 0; i < count; ++i) {
buy[i] = -prices[0];
sell[i] = 0;
}
for (int i = 1; i < len; ++i) {
buy[0] = max(buy[0], -prices[i]);
sell[0] = max(sell[0], buy[0] + prices[i]);
for (int j = count - 1; j > 0; --j) {
buy[j] = max(buy[j], sell[j - 1] - prices[i]);
sell[j] = max(buy[j] + prices[i], sell[j]);
}
}
return sell[count - 1];
}
};
官方给出的最短时间方案:
/*
三种状态:
1.已经进行多少次交易;
2.当前是否买入股票
3.当前持有的股票是否没有卖掉
所以用两个二维数组表示
状态表示:
f[i][k]:前i天进行k次交易,并且股票已经卖出去,
g[i][k]:前i天进行k次交易,并且股票还没有卖出去
状态转移:
f[i][k] =max(f[i-1][k],g[i-1][k]+prices[i]); //一次交易包括买卖两种方式
g[i][k] =max(f[i-1][k-1]-prices[i],g[i-1][k])
优化:
二维化为一维,
*/
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int n=prices.size();
if(n<=1)return 0;
if(k>=n/2){
int sum=0;
for(int i=1;i<n;i++){
if(prices[i] > prices[i-1])sum += (prices[i]-prices[i-1]);
}
return sum;
}
vector<int> f(k+1,0),g(k+1,INT_MIN);
for (auto x:prices)
for (int i=k;i;i--){
f[i]=max(f[i],g[i]+x);
g[i]=max(f[i-1]-x, g[i]);
}
return f[k];
}
};
两种方案差的不多,都定义了买入dp和卖出dp。