# 122. Best Time to Buy and Sell Stock II

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-Mf23Cs7vMhO9vMvhjXf%2F-Mf28ZZipujj3C-1jAjv%2Fimage.png?alt=media\&token=1b2872ba-7aae-4d11-b1a2-1b72050ba3eb)

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-Mf23Cs7vMhO9vMvhjXf%2F-Mf28cltpZh6ULgWbhE9%2Fimage.png?alt=media\&token=a9ad3776-3af5-49bb-b570-468938b3b6d8)



## DP

time: O(n)

space:O(n)

```java
class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        
        int dp[][] = new int[n][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        
        for (int i = 1; i < n ; i++) {
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1] + prices[i]);
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] - prices[i]);
        }
        return dp[n-1][0];
    }
}
```



## use variable

注意到上面的狀態轉移方程中，每一天的狀態只與前一天的狀態有關，而與更早的狀態都無關，因此我們不必存儲這些無關的狀態，

只需要將  **dp\[i-1] \[0] ,  dp\[i-1] \[1] 存放在兩個變量**中，通過它們計算出&#x20;

dp\[i] \[0], dp \[ i ] \[ 1 ] 並存回對應的變量

```java
class Solution {
    public int maxProfit(int[] prices) {
        int n = prices.length;
        
        int dp0 = 0;
        int dp1 = -prices[0];
        
        for (int i = 1; i < n ; i++) {
            int newDp0 = Math.max(dp0, dp1 + prices[i]);
            int newDp1 = Math.max(dp1, dp0 - prices[i]);
            dp0 = newDp0;
            dp1 = newDp1;
        }
        return dp0;
    }
}
```
