> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/greedy/55.-jump-game.md).

# 55. Jump Game

![](/files/-MeZWQrhQ7pNTnOTg2xd)

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