Header Ad

Leetcode Jump Game problem solution

In this Leetcode Jump Game problem solution, we have 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.

leetcode 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;
}


Post a Comment

0 Comments