32代码随想录训练营day32|贪心算法part02

1、买卖股票的最佳时机Ⅱ

买卖股票的最佳时机Ⅱ

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

2、跳跃游戏

跳跃游戏

class Solution {
public:
    bool canJump(vector<int>& nums) {
        int cover = 0;
        for (int i = 0; i <= cover; i++) {
            cover = max(i + nums[i], cover);
            if (cover >= nums.size() - 1) return true;
        }
        return false;
    }
};

3、跳跃游戏2

跳跃游戏2

class Solution {
public:
    int jump(vector<int>& nums) {
        if (nums.size() == 1) return 0;
        int count = 0;
        int nextCover = 0;
        int curCover = 0;
        for (int i = 0; i < nums.size(); i++) {
            nextCover = max(nextCover, nums[i] + i);
            if (i == curCover) {
                count++;
                curCover = nextCover;
                if (nextCover >= nums.size() - 1) {
                    break;
                }
            }
        }
        return count;
    }
};

你可能感兴趣的:(代码随想录训练营,贪心算法,算法,c++,leetcode)