From 7123ab82447fad9c1e387f3478905fe6aea7e852 Mon Sep 17 00:00:00 2001 From: wzs <1014355013@qq.com> Date: Wed, 12 May 2021 23:23:13 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A00123.=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?III=E5=92=8CJava=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0123.买卖股票的最佳时机III.md | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index 0e718cf1..f6d2efb0 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -190,9 +190,42 @@ dp[1] = max(dp[1], dp[0] - prices[i]); 如果dp[1]取dp[1],即保持买入股 ## 其他语言版本 - Java: +```java +class Solution { // 动态规划 + public int maxProfit(int[] prices) { + // 可交易次数 + int k = 2; + + // [天数][交易次数][是否持有股票] + int[][][] dp = new int[prices.length][k + 1][2]; + + // badcase + 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][2][0] = 0; + dp[0][2][1] = Integer.MIN_VALUE; + + for (int i = 1; i < prices.length; i++) { + for (int j = 2; 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 < 3; i++) { + res = Math.max(res, dp[prices.length - 1][i][0]); + } + return res; + } +} +``` + Python: