代码随想录算法训练营第二十八天|LeetCode 122, 55,45

本文介绍了如何使用贪心算法解决LeetCode中的两个问题:122.买卖股票的最佳时机II和55/45.跳跃游戏系列。通过Java代码示例,展示了如何在股票交易中找到最大利润和判断最少跳跃次数来覆盖数组。

目录

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

LeetCode 55. 跳跃游戏

LeetCode 45.跳跃游戏II 


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

文章讲解:代码随想录

视频讲解:贪心算法也能解决股票问题!LeetCode:122.买卖股票最佳时机II_哔哩哔哩_bilibili

力扣题目:LeetCode 122.买卖股票的最佳时机II 

 

代码如下(Java):

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. 跳跃游戏

文章讲解:代码随想录

视频讲解:贪心算法,怎么跳跃不重要,关键在覆盖范围 | LeetCode:55.跳跃游戏_哔哩哔哩_bilibili

力扣题目:LeetCode 55. 跳跃游戏

 

代码如下(Java):

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 

文章讲解:代码随想录

视频讲解:贪心算法,最少跳几步还得看覆盖范围 | LeetCode: 45.跳跃游戏II_哔哩哔哩_bilibili

力扣题目: LeetCode 45.跳跃游戏II 

 

 代码如下(Java):

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;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值