力扣算法学习day23-2

力扣算法学习day23-2

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

题目

image-20220212162223446

image-20220212162245941

代码实现

class Solution {
    public int maxProfit(int[] prices) {
        // 局部最优-->总体最优,局部后一天有赚则买,然后第二天卖。总体则最大利润。0ms
        int[] change = new int[prices.length];
        int sum = 0;

        for(int i = 1;i < prices.length;i++){
            change[i] = prices[i] - prices[i-1];
        }

        for(int i = 1;i < change.length;i++){
            if(change[i] > 0){
                sum += change[i];
            }
        }

        return sum;
    }
}

55-跳跃游戏

题目

image-20220212182357986

代码实现

class Solution {
    // 直接想到的方法,速度很慢,主要是想复杂了点。 321ms
    // public boolean canJump(int[] nums) {
    //     // 贪心,局部最优,扫描每个坐标,将其能走到的位置设置+1,故走不到
    //     // 的位置会是0,开头除外,开头需要额外处理。
    //     int[] maybeCollection = new int[nums.length];

    //     for(int i = 0;i < nums.length;i++){
    //         if(i > 0 && maybeCollection[i] == 0){
    //             return false;
    //         }
    //         int value = nums[i];
    //         int index = i+1;
    //         while(value > 0 && index < nums.length){
    //             maybeCollection[index]++;
    //             index++;
    //             value--;
    //         }
    //     }

    //     return true;
    // }

    // 正确贪心,每次到最远距离,看是否能覆盖到终点。 速度 2ms
    public boolean canJump(int[] nums) {
        int scope = 0;// 覆盖范围

        for(int i = 0;i <= scope;i++){
            scope = Math.max(i+nums[i],scope);
            if(scope >= nums.length-1){
                return true;
            }
        }

        return false;
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

人山人

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值