day32 打卡122.买卖股票的最佳时机II 55. 跳跃游戏 45.跳跃游戏II

发布时间 2023-04-01 10:27:07作者: zzzzzzsl

day32 打卡122.买卖股票的最佳时机II 55. 跳跃游戏 45.跳跃游戏II

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

122题目链接

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

55. 跳跃游戏

55题目链接

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

45.跳跃游戏II

45题目链接

class Solution {
    public int jump(int[] nums) {
        int result = 0;
        int cur = 0;
        int next = 0;
        for (int i = 0 ; i<nums.length ; i++) {
            next = Math.max(i+nums[i], next);
            if (i == cur) {
                if (i != nums.length-1) {
                    cur = next;
                    result++;
                    if (cur >= nums.length-1) break;
                } else {
                    break;
                }
            }
        }
        return result;
    }
}

参考资料

代码随想录