# Jump Game

`Dynamic Programming`, `Greedy`

Medium

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` ，可以转化为：

....

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

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

``dp[n-1]``

## Solution

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

``````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.

``````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/

Last updated