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.
Table of Contents
Jump Game Problem Solution
Problem Solution In Python
class Solution:
def canJump(self, nums: List[int]) -> bool:
l = 0
r = nums[l]
x = len(nums)-1
while(r<x):
if l == r: return False
l, r = r, max(i+nums[i] for i in range(l, r+1))
return True
Problem Solution In Java
public class Solution {
public boolean canJump(int[] nums) {
int i = 0;
while(i<nums.length)
{
if(nums[i] == 0&&i!=nums.length-1)
{
return false;
}
int max = Integer.MIN_VALUE;
int next = i+1;
for(int j = 1;j<nums[i]+1;j++)
{
if(i+j>nums.length-1)
{
return true;
}
if(nums[i+j]+j-1>max)
{
max = nums[i+j]+j-1;
next = i+j;
}
}
i = next;
}
return true;
}
}
Problem Solution In C++
class Solution {
public:
bool canJump(vector<int>& nums) {
if(nums.size()==1) return true ;
if(!nums.size()) return false ;
int maxx = 0 ;
bool ans = true ;
for(int i = 0 ; i < nums.size() ; i ++ )
{
if( nums[i] ) maxx = max( maxx , i + nums[i] ) ;
else
{
if( maxx <= i && i != nums.size() - 1 ) {ans = false ; break ; }
}
}
return ans ;
}
};
Problem Solution In C
bool canJump(int* nums, int numsSize) {
int step=nums[0],i=0;
while(step>0 && i<numsSize)
{
i++;
step--;
step = step>nums[i]? step:nums[i];
}
if(i<numsSize-1)
return false;
return true;
}