代码随想录算法训练营Day51|动态规划10

代码随想录算法训练营Day51|动态规划10


文章目录

  • 代码随想录算法训练营Day51|动态规划10
  • 一、121. 买卖股票的最佳时机
  • 二、122. 买卖股票的最佳时机 II


一、121. 买卖股票的最佳时机

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

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

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

你可能感兴趣的:(代码随想录打卡,算法,动态规划)