Iam_Sandeep

Minimum number of jumps DP VVIMP HARD

May 5th, 2022
736
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.09 KB | None | 0 0
  1. #User function Template for python3
  2. class Solution:
  3.     def minJumps(self, arr, n):
  4.         if len(arr)==1:return 0
  5.         if arr[0]==0:return -1
  6.      
  7.         maxreach,jmp,steps=arr[0],1,arr[0]
  8.         for i in range(1,n):
  9.             if i==n-1:return jmp
  10.             maxreach=max(maxreach,i+arr[i])
  11.             steps=steps-1
  12.             if steps==0:
  13.                 jmp+=1
  14.                 '''
  15.                 Here we can understand if i>maxreach:return -1
  16.                 but why i>=maxreach? why not just i>maxreach?
  17.                 Here we have put i==maxreach also fails reaching
  18.                 destination because we computed already
  19.                 the maxreach by dng max(maxreach,i+arr[i) which didnt impact
  20.                 maxreach. So you can not move further
  21.                 '''
  22.                 if i>=maxreach:return -1
  23.                 else:steps=maxreach-i
  24.    
  25.        
  26.  
  27. #{
  28. #  Driver Code Starts
  29. #Initial Template for Python 3
  30. if __name__ == '__main__':
  31.     T=int(input())
  32.     for i in range(T):
  33.         n = int(input())
  34.         Arr = [int(x) for x in input().split()]
  35.         ob = Solution()
  36.         ans = ob.minJumps(Arr,n)
  37.         print(ans)
  38. # } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment