其他分享
首页 > 其他分享> > 122. 买卖股票的最佳时机II

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

作者:互联网

贪心

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/

标签:明天,int,money,复杂度,II,122,最佳时机,prices,贪心
来源: https://www.cnblogs.com/taoyuann/p/15934790.html