From eacf15d7a3a8042eb8c0181c9d7fb8a438f39e17 Mon Sep 17 00:00:00 2001 From: LiHua <1985390347@qq.com> Date: Wed, 24 Nov 2021 09:31:54 +0800 Subject: [PATCH] =?UTF-8?q?=E5=A2=9E=E5=8A=A0=E4=BA=86122=E4=BC=98?= =?UTF-8?q?=E5=8C=96=E7=A9=BA=E9=97=B4=E7=9A=84java=E9=A2=98=E8=A7=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../0122.买卖股票的最佳时机II.md | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/problems/0122.买卖股票的最佳时机II.md b/problems/0122.买卖股票的最佳时机II.md index d4575bd6..5b117563 100644 --- a/problems/0122.买卖股票的最佳时机II.md +++ b/problems/0122.买卖股票的最佳时机II.md @@ -167,6 +167,25 @@ 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