diff --git a/problems/0188.买卖股票的最佳时机IV.md b/problems/0188.买卖股票的最佳时机IV.md index 11c5805b..937aee3a 100644 --- a/problems/0188.买卖股票的最佳时机IV.md +++ b/problems/0188.买卖股票的最佳时机IV.md @@ -25,7 +25,7 @@ 输入:k = 2, prices = [3,2,6,5,0,3] 输出:7 解释:在第 2 天 (股票价格 = 2) 的时候买入,在第 3 天 (股票价格 = 6) 的时候卖出, 这笔交易所能获得利润 = 6-2 = 4。随后,在第 5 天 (股票价格 = 0) 的时候买入,在第 6 天 (股票价格 = 3) 的时候卖出, 这笔交易所能获得利润 = 3-0 = 3 。 -  + 提示: @@ -167,9 +167,48 @@ public: ## 其他语言版本 - Java: +```java +class Solution { //动态规划 + public int maxProfit(int k, int[] prices) { + if (prices == null || prices.length < 2 || k == 0) { + return 0; + } + + // [天数][交易次数][是否持有股票] + int[][][] dp = new int[prices.length][k + 1][2]; + + // bad case + dp[0][0][0] = 0; + dp[0][0][1] = Integer.MIN_VALUE; + dp[0][1][0] = 0; + dp[0][1][1] = -prices[0]; + // dp[0][j][0] 都均为0 + // dp[0][j][1] 异常值都取Integer.MIN_VALUE; + for (int i = 2; i < k + 1; i++) { + dp[0][i][0] = 0; + dp[0][i][1] = Integer.MIN_VALUE; + } + + for (int i = 1; i < prices.length; i++) { + for (int j = k; j >= 1; j--) { + // dp公式 + dp[i][j][0] = Math.max(dp[i - 1][j][0], dp[i - 1][j][1] + prices[i]); + dp[i][j][1] = Math.max(dp[i - 1][j][1], dp[i - 1][j - 1][0] - prices[i]); + } + } + + int res = 0; + for (int i = 1; i < k + 1; i++) { + res = Math.max(res, dp[prices.length - 1][i][0]); + } + + return res; + } +} +``` + Python: