https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/
请教了一个ACM金的好基友... dp还是一直太弱
思路:
dp[i][j][0]表示前i天,进行j次买和j次卖,也就是进行了完整的j次交易
dp[i][j][1]表示前i天,进行j次买和j-i次卖
那么
dp[i][j][1] = max( dp[i-1][j][1], dp[i-1][j-1][0] - prices[i] ),j>=1 && j <= k
dp[i][j][0] = max( dp[i-1][j][0], dp[i-1][j][1] + prices[i] ), j>=1 && j <= k
实际i这一个维度存储上是不必要的
简化的方程:
dp[j][1] = max( dp[j-1][0] - prices[i] ), j>=1 && j <= k
dp[j][0] = max( dp[j][1] + prices[i] ), j>=1 && j <= k
const int SZ = 1e6 + 5;
int dp[SZ][2];
// 1: buy 0:sell
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
int ans = 0;
if (k >= prices.size()/2) {
for (int i = 1; i < prices.size(); i++) {
if (prices[i] > prices[i-1]) {
ans += prices[i] - prices[i-1];
}
}
return ans;
}
for (int i = 0; i <= k; i++ ) {
dp[i][1] = INT_MIN;
dp[i][0] = 0;
}
for (int i = 0; i < prices.size(); i++) {
for (int j = 1; j <= k; j++) {
int tmp = dp[j][1];
dp[j][1] = max(dp[j][1], dp[j-1][0] - prices[i]);
dp[j][0] = max(dp[j][0], tmp + prices[i]);
}
}
return dp[k][0];
}
};