55. Jump Game

greedy

time: O(n)

space: O(1)

class Solution {
    public boolean canJump(int[] nums) {
        // use greedy 
        // max reach position index = max steps + current position = nums[i] + i
        // so in next round, if current position index > max reach position index, it cant reach this position
        
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i > max) return false;
            max = Math.max(max, nums[i] + i);
        }
        return true;
    }
}
 0 1 2 3 4 => i > max => 4 > max
[3,2,1,0,4]
 3 3 3 3 

faster than 100%

class Solution {
    public boolean canJump(int[] nums) {
        int max = 0;
        for (int i = 0; i < nums.length; i++) {
            if (i > max) return false;
            if (max >= nums.length - 1) return true; // 達到終點提早返回結果
            max = Math.max(max, i + nums[i]);
        }
        return true;
    }
}

Last updated