Jump Game II

This page explains Java solution to problem Jump Game II using Greedy algorithm.

Problem Statement

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.

Your goal is to reach the last index in the minimum number of jumps.

Example 1:

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


If you have any suggestions in below code, please create a pull request by clicking here.

package com.vc.hard;

class JumpGameIi {
    public int jump(int[] nums) {
        if(nums == null || nums.length < 2) return 0;

        int jumps = 0, farthestWithMinimumJump = 0, farthestAtIndex = 0;
        for(int i = 0; i < nums.length - 1; i++) {
            farthestAtIndex = Math.max(farthestAtIndex, i + nums[i]);
            if(i >= farthestWithMinimumJump) {
                farthestWithMinimumJump = farthestAtIndex;
        return jumps;

Time Complexity

Where N is total number of elements in an input array

Space Complexity