From b18f227ffb572c08db29f54f66bbc149b5a68d11 Mon Sep 17 00:00:00 2001 From: LiHua <1985390347@qq.com> Date: Thu, 25 Nov 2021 21:26:43 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=86=E8=AF=AF=E6=B7=BB=E5=8A=A0=E5=88=B012?= =?UTF-8?q?2=E8=B4=AA=E5=BF=83=E7=9A=84java=E7=A9=BA=E9=97=B4=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E4=BB=A3=E7=A0=81=E5=8A=A0=E5=88=B0=E4=BA=86122?= =?UTF-8?q?=E5=8A=A8=E6=80=81=E8=A7=84=E5=88=92=E5=A4=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0122.买卖股票的最佳时机II.md | 19 ------------ ...票的最佳时机II(动态规划).md | 29 +++++++++++-------- 2 files changed, 17 insertions(+), 31 deletions(-) diff --git a/problems/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index 1259aff7..f6d5906a 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -167,25 +167,6 @@ class Solution { // 动态规划 } ``` -```java -// 优化空间 -class Solution { - public int maxProfit(int[] prices) { - int[] dp = new int[2]; - // 0表示持有,1表示卖出 - dp[0] = -prices[0]; - dp[1] = 0; - for(int i = 1; i <= prices.length; i++){ - // 前一天持有; 或当天卖出然后买入 - dp[0] = Math.max(dp[0], dp[1] - prices[i-1]); - // 前一天卖出; 或当天卖出,当天卖出,得先持有 - dp[1] = Math.max(dp[1], dp[0] + prices[i-1]); - } - return dp[1]; - } -} -``` - Python: ```python diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index e701a821..8f03e88e 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -147,25 +147,30 @@ class Solution } return dp[n - 1][0]; // 卖出股票收益高于持有股票收益,因此取[0] } +} +``` - // 实现2:变量存储 - // 第一种方法需要用二维数组存储,有空间开销,其实关心的仅仅是前一天的状态,不关注更多的历史信息 - // 因此,可以仅保存前一天的信息存入 dp0、dp1 这 2 个变量即可 - // 时间复杂度:O(n),空间复杂度O(1) +```java +// 优化空间 +class Solution { public int maxProfit(int[] prices) { - int n = prices.length; - int dp0 = 0, dp1 = -prices[0]; // 定义变量,存储初始状态 - for (int i = 1; i < n; ++i) { - int newDp0 = Math.max(dp0, dp1 + prices[i]); // 第 i 天,没有股票 - int newDp1 = Math.max(dp1, dp0 - prices[i]); // 第 i 天,持有股票 - dp0 = newDp0; - dp1 = newDp1; + int[] dp = new int[2]; + // 0表示持有,1表示卖出 + dp[0] = -prices[0]; + dp[1] = 0; + for(int i = 1; i <= prices.length; i++){ + // 前一天持有; 既然不限制交易次数,那么再次买股票时,要加上之前的收益 + dp[0] = Math.max(dp[0], dp[1] - prices[i-1]); + // 前一天卖出; 或当天卖出,当天卖出,得先持有 + dp[1] = Math.max(dp[1], dp[0] + prices[i-1]); } - return dp0; + return dp[1]; } } ``` + + Python: > 版本一: