Day32 贪心 LeetCode 122 55 45

64 阅读1分钟

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

心得

  • 拆分单挑正向利润即可,AC

题解

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

55. 跳跃游戏

心得

  • 类似青蛙跳台阶,但是贪心想不到

题解

  • 贪心就是每次跳最大——即取最大覆盖范围,然后更新覆盖范围,能覆盖即能达到结果
  • 细节:循环以以覆盖范围为止,单个元素单独判断,每次可调的范围不一定需要在区间size内,可高于
class Solution {
public:
    bool canJump(vector<int>& 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<int>& nums) {
        if (nums.size() == 1) return 0;
        int result = 0;
        int curDistance = 0;
        int nextDistance = 0;
        for (int i = 0; i < nums.size(); i++) {
            nextDistance = max(i + nums[i], nextDistance); // 更新下一次的覆盖范围
            if (i == curDistance) { 
                if (i != nums.size() - 1) { // 没有遍历到结尾,增跳一次
                    result++;
                    curDistance = nextDistance; // 更新当前覆盖范围
                    if (nextDistance >= nums.size() - 1) break; // 能覆盖到结尾
                } else break;
            }
        }
        return result;
    }
};