买卖股票Ⅲ
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iii/
无语了。。。
写的很好就是怎么都过不了。。。
还是就用代码随想录的写法吧。。。
class Solution {
public:int maxProfit(vector<int>& prices) {int n = prices.size();vector<vector<int>> dp(n, vector<int> (5, 0));dp[0][1] = -prices[0];dp[0][3] = -prices[0];for (int i = 1; i < n; i++) {dp[i][0] = dp[i - 1][0];dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);dp[i][2] = max(dp[i - 1][2], dp[i - 1][1] + prices[i]);dp[i][3] = max(dp[i - 1][3], dp[i - 1][2] - prices[i]);dp[i][4] = max(dp[i - 1][4], dp[i - 1][3] + prices[i]);}return *max_element(dp.back().begin(), dp.back().end()); }
};
买卖股票Ⅳ
https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-iv/description/
根据Ⅲ找规律:
class Solution {
public:int maxProfit(int k, vector<int>& prices) {int n = prices.size();vector<vector<int>> dp(n, vector<int>(2 * k + 1, 0));for (int i = 0; i < 2*k+1; i++) {if (i % 2 != 0) dp[0][i] = -prices[0];}for (int i = 1; i < n; i++) {dp[i][0] = dp[i - 1][0];for (int j = 1; j < 2*k+1; j++) {if (j % 2 != 0) dp[i][j] = max(dp[i-1][j], dp[i-1][j-1] - prices[i]);else dp[i][j] = max(dp[i-1][j], dp[i-1][j-1] + prices[i]);}}return *max_element(dp.back().begin(), dp.back().end()); }
};