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 {