122. 买卖股票的最佳时机 II

image.png

动态规划

  1. class Solution {
  2. public int maxProfit(int[] prices) {
  3. int size = prices.length;
  4. int [][] dp = new int[size][2];
  5. dp[0][0] = -prices[0];
  6. //不持有股票
  7. dp[0][1] = 0;
  8. for(int i = 1; i < size; i++ ) {
  9. //多次买卖(第i天买入股票的时候,所持有的现金可能有之前买卖过的利润)
  10. dp[i][0] = Math.max(dp[i - 1][0],dp[i-1][1] - prices[i]);
  11. dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
  12. }
  13. return dp[size - 1][1];
  14. }
  15. }

优化空间

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]);

            dp[1] = Math.max(dp[1],dp[0] + prices[i]);
        }

        return dp[1];
    }
}