Day32 贪心算法 part02

文章讲述了作者在解决两个股票交易问题(买卖股票的最佳时机II)和一个跳跃游戏(跳跃游戏及跳跃游戏II)中,采用贪心算法的思路,通过比较、记录当前和下一个可能的最大步数来求解最优解的过程。
摘要由CSDN通过智能技术生成

Day32 贪心算法 part02

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

我的思路:
只有当后一天比前一天价格高时,才出售,profit才累加

解答:

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

55. 跳跃游戏

我的思路:
想简单了,没有考虑到step指的是最大跳跃格数,可以跳小,[2, 5, 0, 0] 这个例子过不去
后来还是老实按照题解,先把maxJump算出来,和当前i进行对比

解答:

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

45.跳跃游戏 II

我的思路:
把当前i下一个最大跳转数记录下来,当到了该位置的时候,进行跳转并计数

解答:

class Solution {
    public int jump(int[] nums) {
        if(nums == null) {
            return 0;
        }
        int currMax = 0;
        int nextMax = 0;
        int count = 0;
        for(int i = 0; i < nums.length - 1; i++) {
            nextMax = Math.max(nextMax, i + nums[i]);
            if(currMax == i) {
                currMax = nextMax;
                count++;
            }
        }
        return count;
    }
}
  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值