55. Jump Game

1. 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.

2. Example

Example 1:
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.

Example 2:
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.

3. Constraints

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

4. Solutions

My Accepted Solution

n is the number of values in nums
Time complexity: O(n)
Space complexity: O(n)

class Solution {
public:
    bool canJump(const vector<int> &nums) {
        for (int i = 0, max_right = 0; i < nums.size() && i <= max_right; ++i) {
            max_right = max(i + nums[i], max_right);
            if (max_right >= nums.size() - 1) {
                return true;
            }
        }

        return false;
    }
};
comments powered by Disqus