代码随想录算法训练营day34 | 122.买卖股票的最佳时机II 55. 跳跃游戏

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

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

 55. 跳跃游戏

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

45.跳跃游戏II 

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

你可能感兴趣的:(算法,leetcode,c++)