代码随想录算法训练营 day 49: ● 121. 买卖股票的最佳时机 ● 122.买卖股票的最佳时机II

45 阅读1分钟

121. Best Time to Buy and Sell Stock

只能买卖一次。那么dp[i]即为第i天卖出的最大获利。 用一个min值记录扫描过的最小值。 感觉用了个假DP。

class Solution {
    public int maxProfit(int[] prices) {
        if(prices.length <= 1) {
            return 0;
        }

        int[] dp = new int[prices.length];
        dp[0] = 0;
        
        int mini = prices[0];

        for(int i=1; i<prices.length; i++) {
            dp[i] = Math.max(dp[i-1], prices[i] - mini);
            mini = Math.min(mini, prices[i]); 
        }

        return dp[prices.length - 1] > 0 ? dp[prices.length - 1] : 0;
    }
}

122. Best Time to Buy and Sell Stock II

用DP做的话,可以用二维数组保存每个节点卖与不卖的最大获利。 但题目其实说了一天可以买卖多次,也就是当天就算是买进股票,也可以即刻卖出以获取现金。那就算总资产即可。 如果以总资产算的话,dp[i]就是第i天的最大总资产。那么只需要比较第i天的价格跟前一天。若为上涨,则买卖,否则什么也不做。 还是感觉写了个假dp

class Solution {
    public int maxProfit(int[] prices) {
        int len = prices.length;

        if(len <= 1) {
            return 0;
        }

        int[] dp = new int[len];
        dp[0] = 0;

        for(int i=1; i<len; i++) {
            int diff = prices[i] - prices[i-1];

            if(diff > 0) {
                dp[i] = dp[i-1] + diff;
            }
            else {
                dp[i] = dp[i-1];
            }

        }
        

        return dp[len-1];
    }
}