随想录训练营Day49 | DP - - 121. 买卖股票的最佳时机, 122.买卖股票的最佳时机II

61 阅读1分钟

随想录训练营Day49 | DP - - 121. 买卖股票的最佳时机, 122.买卖股票的最佳时机II

标签: LeetCode闯关记


121. 买卖股票的最佳时机

img_49_1.png

class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        int diff = 0;
        for (int i = 1; i < prices.length; i++) {
            diff = prices[i] - prices[i-1];
            if(diff > 0){
                profit += diff;
            }
        }
        return profit;
    }
}

DP

class Solution {
    public int maxProfit(int[] prices) {
       if(prices == null || prices.length == 0)return 0;
       int[][] dp = new int[prices.length][2];
       dp[0][0] = - prices[0];
       dp[0][1] = 0;
        // dp[i][0]代表第i天持有股票的最大收益
        // dp[i][1]代表第i天不持有股票的最大收益
        for (int i = 1; i < prices.length; i++) {
            dp[i][0] = Math.max(dp[i-1][0], -prices[i]);
            System.out.println("i= " + i + "  dp[i][0]=" + dp[i][0]);
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] + prices[i]);
            System.out.println("i= " + i + " dp[i][1]=" + dp[i][1]);
        }
        return dp[prices.length -1][1];
    }
}

注意 dp【i】【0】=max(dp【i-1】【0】,dp【i-1】【1】-prices【i】)
而是dp【i】【0】=max(dp【i-1】【0】,-prices【i】)
因为这样的递推逻辑的设计就刚好实现了股票只能买一次的限定条件

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

class Solution {
    public int maxProfit(int[] prices) {
       if(prices == null || prices.length == 0){
           return 0;
       }
       int[][] dp = new int[prices.length][2];
       dp[0][0] = -prices[0];//持有
        dp[0][1] = 0; //不持有
        for (int i = 1; i < prices.length ; i++) {
            dp[i][0] = Math.max(dp[i-1][0], dp[i-1][1]-prices[i]);//cf:121. 买卖股票的最佳时机"-prices[i]"
            dp[i][1] = Math.max(dp[i-1][1], dp[i-1][0] + prices[i]);
        }
        return dp[prices.length-1][1];
    }
}