From 9287b6be6f3dbcae30e3d5e8c636af24b41a3a7c Mon Sep 17 00:00:00 2001 From: Terry Liu <102352821+Lozakaka@users.noreply.github.com> Date: Tue, 6 Jun 2023 19:25:22 -0400 Subject: [PATCH] =?UTF-8?q?=E6=96=B0=E5=A2=9EJAVA=202*2=E6=95=B8=E7=B5=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit //DP using 2*2 Array (下方還有使用一維滾動數組的更優化版本) --- ...股票的最佳时机II(动态规划).md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/problems/0122.买卖股票的最佳时机II(动态规划).md b/problems/0122.买卖股票的最佳时机II(动态规划).md index 146c6a4c..70ab8364 100644 --- a/problems/0122.买卖股票的最佳时机II(动态规划).md +++ b/problems/0122.买卖股票的最佳时机II(动态规划).md @@ -154,7 +154,24 @@ class Solution } } ``` +```java +//DP using 2*2 Array (下方還有使用一維滾動數組的更優化版本) +class Solution { + public int maxProfit(int[] prices) { + int dp[][] = new int [2][2]; + //dp[i][0]: holding the stock + //dp[i][1]: not holding the stock + dp[0][0] = - prices[0]; + dp[0][1] = 0; + for(int i = 1; i < prices.length; i++){ + dp[i % 2][0] = Math.max(dp[(i - 1) % 2][0], dp[(i - 1) % 2][1] - prices[i]); + dp[i % 2][1] = Math.max(dp[(i - 1) % 2][1], dp[(i - 1) % 2][0] + prices[i]); + } + return dp[(prices.length - 1) % 2][1]; + } +} +``` ```java // 优化空间 class Solution {