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

动态规划

class Solution {
    public int maxProfit(int[] prices) {

        int[][] dp = new int[prices.length][2];

        dp[0][0] = -prices[0];
        dp[0][1] = 0;

        /**
         * 和《121. 买卖股票的最佳时机》相比只有一处不同
         * 对于第i天,如果持有,可能是前一天就持有了,或者是前一天没有持有今天买,二者取最大值(可以多次买卖,因此前一天没持有利润是dp[i - 1][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]);
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] + prices[i]);
        }

        return dp[prices.length - 1][1];
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

贪心

class Solution {
    public int maxProfit(int[] prices) {

        int money = 0;

        for (int i = 0; i + 1 < prices.length; i++) {

            /**
             * 贪心思路
             * 局部最优:收集每天的正利润,全局最优:求得最大利润。
             * 只要今天的价格比明天大,就略过
             * 否则就今天买,明天卖,然后明天继续判断
             */
            if (prices[i] >= prices[i + 1]) {
                continue;
            }
            else {
                money += prices[i + 1] - prices[i];
            }
        }

        return money;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/

posted @ 2022-02-25 10:25  振袖秋枫问红叶  阅读(31)  评论(0)    收藏  举报