imashutosh51

Minimum steps to reach end of array

Jul 23rd, 2022 (edited)
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. '''
  2. Time complexity: O(n)
  3. We use a greedy level by level approach where r represents the current range of indices reachable with the current number of jumps.
  4. For all indices in this range, we compute the farthest index we can reach next, Then we move the right max range with to r and increase the jump count.
  5. This continues until the right boundary reaches or crosses the last index.class Solution:
  6. '''
  7. class Solution:
  8.     def jump(self, nums: List[int]) -> int:
  9.         if len(nums)==1:
  10.             return 0
  11.         r=nums[0]
  12.         max_range=nums[0]
  13.         ans=1
  14.         for i in range(1,len(nums)-1): #We don't have to jump from the last index, we just need to reach there so keeping len(nums)-1
  15.             max_range=max(max_range,i+nums[i])
  16.             if i==r:
  17.                 ans+=1
  18.                 r=max_range
  19.         return ans
  20.            
  21.        
Advertisement
Add Comment
Please, Sign In to add comment