Jump Game - Java Solution

1. Introduction

This blog post explores the "Jump Game" problem, a popular challenge in array manipulation and dynamic programming. The problem involves an array where each element indicates the maximum jump length from that position. The task is to determine whether it's possible to reach the end of the array starting from the first index.

Problem

Given an integer array nums, where each element represents the maximum jump length at that position, the objective is to return true if you can reach the last index of the array, or false otherwise.

2. Solution Steps

1. Use a greedy approach to solve the problem.

2. Initialize a variable maxReach to keep track of the farthest index that can be reached.

3. Iterate through each element of the array and update maxReach accordingly.

4. If at any point, maxReach is less than the current index, return false, as it's not possible to move forward.

5. If the end of the array is reached or maxReach is beyond the end, return true.

6. The key is to always maintain the farthest reachable index while iterating through the array.

3. Code Program

public class JumpGame {
    public static void main(String[] args) {
        int[] nums = {2, 3, 1, 1, 4};
        System.out.println(canJump(nums)); // Test the function
    }

    // Function to determine if it's possible to reach the end of the array
    public static boolean canJump(int[] nums) {
        int maxReach = 0;

        for (int i = 0; i < nums.length; i++) {
            if (maxReach < i) return false; // Cannot jump further
            maxReach = Math.max(maxReach, i + nums[i]);
        }
        return true;
    }
}

Output:

true

Explanation:

1. canJump: This function checks whether the last index of the array is reachable from the first index.

2. It initializes maxReach to track the furthest index that can be reached at any point.

3. As it iterates through the array, the function updates maxReach to the maximum of its current value and the index plus jump length from that index.

4. If at any point maxReach is less than the current index, it means the journey cannot continue, and the function returns false.

5. If the loop completes without returning false, it implies that the end of the array is reachable, and the function returns true.

6. This greedy approach ensures an efficient solution by always keeping track of the furthest reachable position and validating the possibility of reaching the end.


Comments