I'm solving this leetcode problem (problem no:55):
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 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.
When I submit the code with the commented out for loop, this is running till 75 test cases out of 170 , and says 'Time limit exceeded' as this code is slower. But when I commented out and replaced with the current for loop, it runs faster and says '70% faster than all python submission in leetcode'.
Both for loops looks similar and run the same number of iterations. Why is one faster than the other?
class Solution:
def canJump(self, nums: List[int]) -> bool:
i = 0
n = len(nums)
next = None
if(n==1):
return True
while(i < n):
ni = nums[i]
if(ni==0):
return False
if(i==(n-1)):
break
max = 0
# for j in range(ni):
# imb = i+j+1+nums[i+j+1]
# if(max<imb):
# max = imb
# next = i+j+1
#
# if(max >= (n-1)):
# return True
for j in range(i, i+nums[i]+1):
if j+(nums[j]) >= max:
max = j+(nums[j])
next = j
if(max >= (n-1)):
return True
i = next
return False