Woodstock Blog

a tech blog for general algorithmic interview questions

[LeetCode 55] Jump Game

Question

link

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.

For example:
A = [2,3,1,1,4], return true.

A = [3,2,1,0,4], return false.

Stats

Frequency 2
Difficulty 3
Adjusted Difficulty 1
Time to use ----------

Ratings/Color = 1(white) 2(lime) 3(yellow) 4/5(red)

Analysis

This is a standard DP problem.

My code

public class Solution {
    public boolean canJump(int[] A) {
        if (A == null || A.length <= 1) {
            return true;
        }
        int len = A.length;
        int left = 0;
        int right = 0;
        while (left <= right && right < len -1) {
            right = Math.max(right, left + A[left]);
            left++;
        }
        return right >= len - 1;
    }
}