栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

前言

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

参考题解:买卖股票的最佳时机 II-代码随想录

提交代码

因为之前做过leetcode 376 摆动序列,所以很自然想到,使用贪心策略,累加求和所有的上坡(局部谷底->局部峰值)差值。

class Solution {
public:
    int maxProfit(vector& prices) {
        // 贪心策略:在波动的低估买入,峰值卖出
        // 策略证明:不放过每个赚钱的机会
        int result = 0;
        int low,high;
        for(int i=0; i prices[i]){ // 在上坡
                low = i;
                while(i prices[i]) // 循环退出时,i在当前坡的峰值
                    i++;
                high = i;
                result += (prices[high] - prices[low]);
            }
        }

        return result;
    }
};

上面的贪心策略,等价于“局部最优:收集每天的正利润,全局最优:求得最大利润”。

下面代码来自参考题解。

class Solution {
public:
    int maxProfit(vector& prices) {
        int result = 0;
        for (int i = 1; i < prices.size(); i++) {
            result += max(prices[i] - prices[i - 1], 0);
        }
        return result;
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/295546.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号