LeeCode打卡第三十七天

LeeCode打卡第三十七天

第一题:买卖股票的最佳时机II(LeeCode第122题):

给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。返回 你能获得的 最大 利润

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

第二题:跳跃游戏(LeeCode第55题):

给你一个非负整数数组 nums ,你最初位于数组的 第一个下标 。数组中的每个元素代表你在该位置可以跳跃的最大长度。判断你是否能够到达最后一个下标,如果可以,返回 true ;否则,返回 false 。


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

第三题:跳跃游戏II(Leecode第45题)

给定一个长度为 `n` 的 **0 索引**整数数组 `nums`。初始位置为 `nums[0]`。每个元素 `nums[i]` 表示从索引 `i` 向前跳转的最大长度。换句话说,如果你在 `nums[i]` 处,你可以跳转到任意 `nums[i + j]` 处:

  • 0 <= j <= nums[i]
  • i + j < n
返回到达 nums[n - 1] 的最小跳跃次数。生成的测试用例可以到达 nums[n - 1]。

class Solution {
    public int jump(int[] nums) {
        int curDistance = 0;
        int ans = 0;
        int nextDistance = 0;
        for(int i = 0; i < nums.length - 1; i++){
            nextDistance = Math.max(i + nums[i], nextDistance);
            if(i == curDistance){
                curDistance = nextDistance;
                ans++;
            }
        }
        return ans;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值