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

题目
文章讲解
视频讲解

思路:
在这里插入图片描述移动下标达到了当前覆盖的最远距离下标时,步数就要加一,来增加覆盖距离。最后的步数就是最少步数。

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

  • 如果当前覆盖最远距离下标不是是集合终点,步数就加一,还需要继续走。
  • 如果当前覆盖最远距离下标就是是集合终点,步数不用加一,因为不能再往后走了。
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;
    }
}

最近更新

  1. TCP协议是安全的吗?

    2024-01-28 22:48:03       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-28 22:48:03       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-28 22:48:03       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-28 22:48:03       20 阅读

热门阅读

  1. C#中类型装换

    2024-01-28 22:48:03       30 阅读
  2. C语言2024-1-27练习记录

    2024-01-28 22:48:03       28 阅读
  3. Windows OpenVPN的安装之桥接模式

    2024-01-28 22:48:03       28 阅读
  4. 【C语言】分支循环语句

    2024-01-28 22:48:03       33 阅读
  5. C语言sizeof和strlen区别

    2024-01-28 22:48:03       46 阅读
  6. uniapp微信小程序-前端设计模式学习(中)

    2024-01-28 22:48:03       31 阅读