Skip to content

Latest commit

 

History

History
61 lines (44 loc) · 1.54 KB

LC55.md

File metadata and controls

61 lines (44 loc) · 1.54 KB

Problem: Jump Game

Difficulty: Medium

Description:

Given an array of non-negative integers nums, 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.

Examples:

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.

Constraints:

1 <= nums.length <= 3 * 10^4
0 <= nums[i] <= 10^5

Solutions:

For the DP approach we traverse the array nums and we define a flag can_reach with a value of 0. For each value in the array nums, the maximum jump would be nums[i]. So, we check if the flag is greater than equal the index of the array and we maximize the value between flag and i + nums[i]. The time complexity of this solution is O(N) and the space complexity is O(1) where N is the length of the array nums.

def canJump(self, nums):
    """
    :type S: str
    :type T: str
    :rtype: bool
    :Time Complexity: O(N)
    :Space Complexity: O(1)
    """
    N = len(nums) - 1
    can_reach = 0

    if len(nums) == 1:
        return True

    for i in range(N):
        if can_reach >= i:
            can_reach = max(can_reach, i + nums[i])

        if can_reach >= N:
            return True

    return False