From 71f1410d8d0d9d71d9208b6a6ee098c70b3d3303 Mon Sep 17 00:00:00 2001 From: LiHua <1985390347@qq.com> Date: Wed, 24 Nov 2021 09:25:23 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BA=86121=E5=8A=A8?= =?UTF-8?q?=E6=80=81=E8=A7=84=E5=88=92=E7=89=88=E6=9C=AC=E4=BA=8C=E7=9A=84?= =?UTF-8?q?=E8=A7=A3=E9=A2=98=E4=BB=A3=E7=A0=81^C=E9=A2=98=E4=BB=A3?= =?UTF-8?q?=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- problems/0121.买卖股票的最佳时机.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index 89f0637a..45b61666 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -249,11 +249,14 @@ class Solution { // 所以我们从 i=1 开始遍历数组,一共有 prices.length 天, // 所以是 i<=prices.length for (int i = 1; i <= prices.length; i++) { - int temp = dp[0]; // 前一天持有;或当天买入 - dp[0] = Math.max(temp, -prices[i - 1]); + dp[0] = Math.max(dp[0], -prices[i - 1]); + // 如果 dp[0] 被更新,那么 dp[1] 肯定会被更新为正数的 dp[1] + // 而不是 dp[0]+prices[i-1]==0 的0, + // 所以这里使用会改变的dp[0]也是可以的 + // 当然 dp[1] 初始值为 0 ,被更新成 0 也没影响 // 前一天卖出;或当天卖出, 当天要卖出,得前一天持有才行 - dp[1] = Math.max(dp[1], temp + prices[i - 1]); + dp[1] = Math.max(dp[1], dp[0] + prices[i - 1]); } return dp[1]; }