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

# 55.Jump-Game

## 55. Jump Game

## 题目地址

<https://www.jiuzhang.com/solutions/jump-game>

## 题目描述

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

## 代码

### Approach #1: Dynamic Programming

```java
public class Solution {
  public boolean canJump(int[] A) {
    boolean[] f = new boolean[A.length];
    f[0] = true;

    for (int i = 1; i < A.length; i++) {
      for (int j = 0; j < i; j++) {
        if (f[j] && j + A[j] >= i) {
          f[i] = true;
          break;
        }
      }
    }
    return f[A.length - 1];
  }
}
```

### Approach #2: Greedy

```java
public class Solution {
  public boolean canJump(int[] A) {
    if (A == null || A.length == 0) {
        return false;
    }

    int farthest = A[0];
    for (int i = 1; i < A.length; i++) {
        if (i <= farthest && A[i] + i >= farthest) {
            farthest = A[i] + i;
        }
    }

    return farthest >= A.length - 1;
  }
}
```

```java
class Solution {
  public boolean canJump(int[] nums) {
    int n = nums.length;
    int maxPos = nums[0];

    for (int i = 1; i < n; i++) {
      if (maxPos < i) {
        return false;
      }
      maxPos = Math.max(maxPos, nums[i] + i);
    }
    return true;
  }
}
```
