Day 32 | 贪心 122.买卖股票的最佳时机II 、55. 跳跃游戏 、 45.跳跃游戏II

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

题目
文章讲解
视频讲解

思路:虽然写的不是特别好,但这是第一道我看着思路自己一遍过的题目诶!好耶!

class Solution {
    public int maxProfit(int[] prices) {
        int cur=0;
        int sum=0;
        for(int i=1;i<prices.length;i++){
            cur=prices[i]-prices[i-1];
            if(cur>0) sum+=cur;
        }
        return sum;
    }
}

55. 跳跃游戏

题目
文章讲解
视频讲解

思路:寻找可覆盖的最大范围,注意 for 循环中 i<=cover

class Solution {
    public boolean canJump(int[] nums) {
        int length = nums.length;
        int cover = 0;
        if (length == 1)
            return true;
        for (int i = 0; i <= cover; i++) {
            cover = Math.max(i + nums[i], cover);
            if (cover >= length - 1)
                return true;
        }
        return false;
    }
}

45.跳跃游戏II

题目
文章讲解
视频讲解

思路:
Day 32 | 贪心 122.买卖股票的最佳时机II 、55. 跳跃游戏 、 45.跳跃游戏II_第1张图片移动下标达到了当前覆盖的最远距离下标时,步数就要加一,来增加覆盖距离。最后的步数就是最少步数。

这里还是有个特殊情况需要考虑,当移动下标达到了当前覆盖的最远距离下标时

  • 如果当前覆盖最远距离下标不是是集合终点,步数就加一,还需要继续走。
  • 如果当前覆盖最远距离下标就是是集合终点,步数不用加一,因为不能再往后走了。
class Solution {
    public int jump(int[] nums) {
        if (nums == null || nums.length == 0 || nums.length == 1)
            return 0;
        int count = 0;
        int curDistance = 0;
        int maxDistance = 0;
        for (int i = 0; i < nums.length; i++) {
            maxDistance = Math.max(maxDistance, i + nums[i]);
            if (maxDistance >= nums.length - 1) {
                count++;
                break;
            }
            if (i == curDistance) {
                curDistance = maxDistance;
                count++;
            }
        }
        return count;
    }
}

你可能感兴趣的:(二月红,力扣,java)