Day28 贪心 | LeetCode 122. 买卖股票的最佳时机 II, 55. 跳跃游戏, 45. 跳跃游戏 II

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

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

LeetCode 55. 跳跃游戏

每次判断最大cover值能不能覆盖到最后
class Solution {
public:
    bool canJump(vector& nums) {
        int index = 0;
        int cover = 0;
        for (int i = 0; i <= cover; i++){
            cover = max(cover, i + nums[i]);
            if (cover >= nums.size() - 1){
                return true;
            }
        }
        return false;
        
    }
};

LeetCode 45. 跳跃游戏 II

自己实现
class Solution {
public:
    int jump(vector& nums) {
        if (nums.size() == 1){
            return 0;
        }
        int maxCover = nums[0];
        int curCover = 0;
        int count = 1;
        int index = 0;
        while (index <= nums.size() - 1){
            if (maxCover >= nums.size() - 1){
                break;
            }
            for (int i = index; i <= maxCover; i++){
                if (nums[i] + i > curCover){
                    curCover = nums[i] + i; 
                    index = i;
                }
            }
            maxCover = curCover;
            count++;
        }
        return count;
    }
};
优化版本
class Solution {
public:
    int jump(vector& nums) {
        int curCover = 0;
        int maxCover = 0;
        int ans = 0;
        for (int i = 0; i < nums.size() - 1; i++){
            maxCover = max(maxCover, nums[i] + i);
            if (i == curCover){
                curCover = maxCover;
                ans++;
            }
        }
        return ans;
    }
};

你可能感兴趣的:(算法学习,leetcode,游戏,算法)