From 4c3b4d8e5e45efa6b226521b4615aa8eb7742185 Mon Sep 17 00:00:00 2001 From: wzs <1014355013@qq.com> Date: Wed, 12 May 2021 23:23:55 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00188.=E4=B9=B0=E5=8D=96?= =?UTF-8?q?=E8=82=A1=E7=A5=A8=E7=9A=84=E6=9C=80=E4=BD=B3=E6=97=B6=E6=9C=BA?= =?UTF-8?q?IV=E5=92=8CJava=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0188.买卖股票的最佳时机IV.md | 43 +++++++++++++++++++++++++-- 1 file changed, 41 insertions(+), 2 deletions(-) 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: