Friday, September 4, 2020

[LeetCode] Jump Game

Problem: You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position.

Return true if you can reach the last index, or false otherwise.

Example:

Input: nums = [2,3,1,1,4]
Output: true
Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index.
Input: nums = [3,2,1,0,4]
Output: false
Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.


Approach: We will start from the last index (length -1) and see if there is an index i from length - 2 to 0 where nums[i] + i is equal to the length - 1. That means can we reach from any index to length - 1. Once we find such good_index, now our task is to check if we can reach from any index (good_index - 1 to 0) to good_index or not. 


Implementation in C#:

    public bool CanJump(int[] nums)
    {
        int length = nums?.Length ?? 0;
        if (length <= 1)
        {
            return true;
        }
        int lastGoodPos = length - 1;
        for (int i = length - 2; i >= 0; --i)
        {
            if (i + nums[i] >= lastGoodPos)
            {
                lastGoodPos = i;
            }
        }
        return lastGoodPos == 0;
    }


Complexity: O(n)

No comments:

Post a Comment