# Jump Game

`Dynamic Programming`, `Greedy`

**Medium**&#x20;

Given an array of non-negative integers, you are initially positioned at the first index of the array.

Each element in the array represents your maximum jump length at that position.

Determine if you are able to reach the last index.

**Example 1:**

```
Input:
 [2,3,1,1,4]

Output:
 true

Explanation:
 Jump 1 step from index 0 to 1, then 3 steps to the last index.
```

**Example 2:**

```
Input:
 [3,2,1,0,4]

Output:
 false

Explanation:
 You will always arrive at index 3 no matter what. Its maximum
             jump length is 0, which makes it impossible to reach the last index.
```

## Analysis

**转化为子问题**：

设`n = nums.length`。问题是否能到达`n - 1` ，可以转化为：

是否`n - 2`能否到达，以及从 `n - 2`是否能到达`n - 1`

或者`n - 3`是否能到达，并且从`n - 2`是否能到达`n - 1`

或者`n - 4`是否能到达，并且从`n - 4`是否能到达`n - 1`

....

或者`0`是否能到达，并且从`0`是否能到达`n - 1`

因此可以设定**动态规划状态**`dp[i]`: 从开始出发能否到达`index = i`

**初始值**`dp[0] = true`, 第一个初始位置一定可以到达

`dp[i] = false`代表`dp[i]`不确定能否到达，需要在后续bottom-up过程中得到答案

那么**转移方程**为：

```java
if (dp[j] && j + nums[j] >= i) {
    dp[i] = true;
    break;
}
```

最终结果则是：

```java
dp[n-1]
```

参考：[https://leetcode.com/articles/jump-game/](https://leetcode.com/articles/jump-game/)

其中还有top-down的记忆化搜索，bottom-up的动态规划，贪心greedy等方法。

## Solution

### DP - Bottom Up

### Time O(n^2), Space O(n)

```java
class Solution {
    public boolean canJump(int[] nums) {
        if (nums == null) return false;
        int n = nums.length;
        boolean dp[] = new boolean[n];

        dp[0] = true; // init

        for (int i = 1; i < n; i++) {
            dp[i] = false;
            for (int j = 0; j < i; j++) {
                if (dp[j] && j + nums[j] >= i) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[n - 1];
    }
}
```

### Greedy

**Complexity Analysis**

* Time complexity : O(n). We are doing a single pass through the`nums`array, hencennsteps, wherennis the length of array`nums`.
* Space complexity : O(1). We are not using any extra memory.

```java
public class Solution {
    public boolean canJump(int[] nums) {
        int lastPos = nums.length - 1;
        for (int i = nums.length - 1; i >= 0; i--) {
            if (i + nums[i] >= lastPos) {
                lastPos = i;
            }
        }
        return lastPos == 0;
    }
}
```

## Reference

[https://leetcode.com/articles/jump-game/](https://leetcode.com/articles/jump-game/)
