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

题目来源:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-ii/description/

力扣 122. 买卖股票的最佳时机 II_第1张图片

 

 C++题解1:贪心算法,可以理解为找摆动序列的上升坡,然后累积坡度。

class Solution {
public:
    int maxProfit(vector& prices) {
        int len = prices.size();
        if(len == 1) return 0;
        int profit = 0;
        int in = 0, out = 0;
        for(int i = 0; i < len-1; i++) {
            if(prices[i+1] > prices[i]) {
                in = prices[i];
                out = prices[i+1];
                while((i+2 < len)&&(prices[i+2]>prices[i+1])){
                    out = prices[i+2];
                    i++;
                }
                profit = profit + out - in;
            }
        }
        return profit;
    }
};

C++题解2(来源代码随想录):贪心算法,计算从第二天开始的正利润。

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;
    }
};

你可能感兴趣的:(开始C++吧,leetcode,算法,c++,贪心算法)