Best Time to Buy and Sell Stock IV
Thoughts
Code
class Solution {
public:
int maxProfit(int k, vector<int>& prices) {
const int N = prices.size();
if (N == 0) return 0;
if (k >= N / 2) {
int res = 0;
for (int i = 1; i < N; ++i) {
if (prices[i] > prices[i - 1]) res += prices[i] - prices[i - 1];
}
return res;
}
vector<vector<int>> buy(N, vector<int>(k + 1)), sell(N, vector<int>(k + 1));
for (int j = 0; j <= k; ++j) buy[0][j] = -prices[0];
for (int i = 1; i < N; ++i) buy[i][0] = max(-prices[i], buy[i - 1][0]);
for (int i = 1; i < N; ++i) {
for (int j = 1; j <= k; ++j) {
buy[i][j] = max(buy[i - 1][j], sell[i - 1][j] - prices[i]);
sell[i][j] = max(sell[i - 1][j], buy[i - 1][j - 1] + prices[i]);
}
}
return sell[N - 1][k];
}
};Analysis
Last updated