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

文章提供了使用贪心算法解决LeetCode中关于股票交易和跳跃游戏的三个问题。具体包括122题买卖股票的最佳时机II,找到每次交易的最大利润;55题跳跃游戏,判断是否能到达数组末尾;以及45题跳跃游戏II,求最小跳跃次数到达数组末尾。每个问题都给出了详细的思路和Java代码实现。
摘要由CSDN通过智能技术生成

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

题目链接
思路:贪心算法,算出每两天的利润,将每两天的正利润相加,则为最大利润
代码

class Solution {
    public int maxProfit(int[] prices) {
        // 贪心算法
        int result = 0;
        for (int i = 1; i < prices.length; i++) {
            // 将每两天为正的利润相加,则为最大利润
            result += Math.max((prices[i] - prices[i - 1]), 0);
        }
        return result;
    }
}

Leetcode 55. 跳跃游戏

题目链接
思路:贪心算法
代码

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

Leetcode 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 nextDistance = 0;
        for (int i = 0; i < nums.length; i++) {
            // 更新下一步覆盖最远距离下标
            nextDistance = Math.max(nums[i] + i, nextDistance);
            // 遇到当前覆盖最远距离下标
            if (i == curDistance) {
                // 如果当前覆盖最远距离下标不是终点
                if (curDistance != nums.length - 1) {
                    count++;
                    // 更新当前覆盖最远距离下标
                    curDistance = nextDistance;
                    // 下一步的覆盖范围已经可以达到终点,结束循环
                    if (nextDistance >= nums.length - 1) {
                        break;
                    }
                } else {
                    // 当前覆盖最远距离下标是集合终点,不用做ans++操作了,直接结束
                    break;
                }
            }
        }
        return count;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值