# 55. Jump Game

![](https://4272748102-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LekNH5IywF8mjBxFcnu%2F-MeY-kOfKtekxM3kpjIc%2F-MeZWQrhQ7pNTnOTg2xd%2Fimage.png?alt=media\&token=2605b7a7-c8b2-4eb3-9109-a9126b66c429)

## greedy

time: O(n)

space: O(1)

```java
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%

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