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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/dynamic-programming/1.position/55.jump-game.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
