From 6bc248031953b214a2d08fc5180938048a099940 Mon Sep 17 00:00:00 2001 From: LiHua <1985390347@qq.com> Date: Wed, 24 Nov 2021 16:26:02 +0800 Subject: [PATCH] =?UTF-8?q?=E6=A0=BC=E5=BC=8F=E5=8C=96=E4=BA=86123?= =?UTF-8?q?=E4=B8=80=E7=BB=B4=E6=95=B0=E7=BB=84=E7=A9=BA=E9=97=B4=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E7=9A=84java=E4=BB=A3=E7=A0=81=EF=BC=8C=E5=B9=B6?= =?UTF-8?q?=E6=9B=B4=E6=AD=A3=E4=BA=86=E6=B3=A8=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0123.买卖股票的最佳时机III.md | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/problems/0123.买卖股票的最佳时机III.md b/problems/0123.买卖股票的最佳时机III.md index db3f0278..3d67ec87 100644 --- a/problems/0123.买卖股票的最佳时机III.md +++ b/problems/0123.买卖股票的最佳时机III.md @@ -221,23 +221,23 @@ class Solution { // 版本二: 空间优化 class Solution { public int maxProfit(int[] prices) { - 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++){ + 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]); + 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[3]; }