From 4fab08d0306d82aef04379ef01b9b08aae65543a Mon Sep 17 00:00:00 2001 From: Terry Liu <102352821+Lozakaka@users.noreply.github.com> Date: Tue, 6 Jun 2023 19:09:57 -0400 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BE=9BJAVA=E7=9A=842*2=E6=95=B8?= =?UTF-8?q?=E7=B5=84=E7=89=88=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原本的空間優化是直接優化成一維數組,故提供一個2*2數組的版本 --- problems/0121.买卖股票的最佳时机.md | 25 +++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/problems/0121.买卖股票的最佳时机.md b/problems/0121.买卖股票的最佳时机.md index 753cb106..794185da 100644 --- a/problems/0121.买卖股票的最佳时机.md +++ b/problems/0121.买卖股票的最佳时机.md @@ -243,8 +243,27 @@ class Solution { } } ``` +> 动态规划:版本二(使用二維數組(和卡哥思路一致),下面還有使用一維滾動數組的更優化版本) -> 动态规划:版本二 +```Java +class Solution { + public int maxProfit(int[] prices) { + int len = prices.length; + int dp[][] = new int[2][2]; + + dp[0][0] = - prices[0]; + dp[0][1] = 0; + + for (int i = 1; i < len; i++){ + dp[i % 2][0] = Math.max(dp[(i - 1) % 2][0], - prices[i]); + dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], prices[i] + dp[(i - 1) % 2][0]); + } + return dp[(len - 1) % 2][1]; + } +} +``` + +> 动态规划:版本二(使用一維數組) ``` java class Solution { @@ -271,6 +290,10 @@ class Solution { } } ``` +```Java + +``` + Python: