代码随想录训练营二刷第五十一天 | 121. 买卖股票的最佳时机 122.买卖股票的最佳时机II

代码随想录训练营二刷第五十一天 | 121. 买卖股票的最佳时机 122.买卖股票的最佳时机II

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

题目链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock/
思路:每天是有两种状态的,定义dp[i][0]表示第i天持有股票手中金额的最大值,dp[i][1]表示第i天不持有股票手中金额的最大值。
注意,这里的持有可以是之前持有的,也可以是当天才持有的,不持有可以是之前就没持有过,也可以说当前才卖出变成了没持有。

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

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

题目链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/
思路:股票问题思路和上一题一样,每一天都是两个状态,持有或者不持有。
定义dp[i][0]标识定i天持有股票手中金额的最大值,dp[i][1]标识第i天不持有股票手中金额的最大值。
持有可以是之前持有的,也可以是今天才持有的。不持有,可以是今天卖出,也可以是之前卖出去的。

class Solution {
   public int maxProfit(int[] prices) {
        int[] dp = new int[2];
        dp[0] = -prices[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];
    }
}

你可能感兴趣的:(力扣算法题,数据结构,算法,动态规划)