From 5fc35368c1feba9a87cea44d603ebb8b646e8654 Mon Sep 17 00:00:00 2001 From: LiHua <1985390347@qq.com> Date: Wed, 24 Nov 2021 09:37:18 +0800 Subject: [PATCH] =?UTF-8?q?=E7=BB=9F=E4=B8=80=E4=BA=86123=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E7=A9=BA=E9=97=B4=E5=86=99=E6=B3=95=E7=9A=84java?= =?UTF-8?q?=E8=A7=A3=E9=A2=98=E4=BB=A3=E7=A0=81=E6=A0=BC=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0123.买卖股票的最佳时机III.md | 41 +++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index 9c269978..db3f0278 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -188,7 +188,7 @@ dp[1] = max(dp[1], dp[0] - prices[i]); 如果dp[1]取dp[1],即保持买入股 ## 其他语言版本 -Java: +### Java ```java // 版本一 @@ -221,25 +221,30 @@ class Solution { // 版本二: 空间优化 class Solution { public int maxProfit(int[] prices) { - int len = prices.length; - int[] dp = new int[5]; - dp[1] = -prices[0]; - dp[3] = -prices[0]; - - for (int i = 1; i < len; i++) { - dp[1] = Math.max(dp[1], dp[0] - prices[i]); - dp[2] = Math.max(dp[2], dp[1] + prices[i]); - dp[3] = Math.max(dp[3], dp[2] - prices[i]); - dp[4] = Math.max(dp[4], dp[3] + prices[i]); + int[] dp=new int[4]; + // 存储两天的状态就行了 + // dp[0]代表第一次买入 + dp[0]=-prices[0]; + // dp[1]代表第一次卖出 + dp[1]=0; + // dp[2]代表第二次买入 + dp[2]=-prices[0]; + // dp[3]代表第二次卖出 + dp[3]=0; + for(int i=1; i<=prices.length; i++){ + // 要么保持不变,要么没有就买,有了就卖 + dp[0]=Math.max(dp[0], -prices[i-1]); + dp[1]=Math.max(dp[1], dp[0]+prices[i-1]); + // 这已经是第二天了,所以得加上前一天卖出去的价格 + dp[2]=Math.max(dp[2], dp[1]-prices[i-1]); + dp[3]=Math.max(dp[3], dp[2]+prices[i-1]); } - - return dp[4]; + return dp[3]; } } ``` - -Python: +### Python > 版本一: ```python @@ -308,7 +313,7 @@ func max(a,b int)int{ -JavaScript: +### JavaScript > 版本一: @@ -347,7 +352,7 @@ const maxProfit = prices => { }; ``` -Go: +### Go > 版本一: ```go @@ -381,5 +386,7 @@ func max(a, b int) int { ``` + + -----------------------