Timeline
Timeline
2025-12-17
init
Dynamic Programming
Problem:
Similar to the following problem:
123456789101112131415161718192021222324252627282930313233 | using std::vector;class Solution { public: int maxProfit(int k, vector<int> &prices) { int i, j, n = prices.size(); int nr_state = 2 * k + 1; if (n == 1) { return 0; } // dp[i][j] represents the maximum profit of the j-th state on the i-th day. vector<vector<int> > dp(n, vector<int>(nr_state, 0)); dp[0][0] = 0; dp[0][1] = -prices[0]; for (j = 2; j < nr_state; j++) { dp[i][j] = -1e9; } for (i = 1; i < n; i++) { dp[i][0] = dp[i - 1][0]; for (j = 1; j < nr_state; j += 2) { dp[i][j] = std::max(dp[i - 1][j], dp[i - 1][j - 1] - prices[i]); } for (j = 2; j < nr_state; j += 2) { dp[i][j] = std::max(dp[i - 1][j], dp[i - 1][j - 1] + prices[i]); } } return *std::max_element(dp[n - 1].begin(), dp[n - 1].end()); }}; |

