美文网首页
122. 买卖股票的最佳时机 II

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

作者: lazy_ccccat | 来源:发表于2020-03-02 12:28 被阅读0次

    题目描述

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

    思路

    这个我还真没思路,看了答案发现是贪心算法,就是做波段,把所有的波段都抓住,就是最大利润了。

    代码

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            if (prices.empty()) return 0;
            int maxProfit = 0;
            for (int i = 1; i < prices.size(); i++) {
                if (prices[i] > prices[i-1]) {
                    maxProfit += (prices[i] - prices[i-1]);
                }
            }
            return maxProfit;
    
        }
    };
    

    相关文章

      网友评论

          本文标题:122. 买卖股票的最佳时机 II

          本文链接:https://www.haomeiwen.com/subject/zscmkhtx.html