imashutosh51

Steps to make Array non-decreasing

Oct 8th, 2022 (edited)
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.73 KB | None | 0 0
  1. '''
  2. Logic:
  3.  
  4. Each element arr[i] will be removed by the nearest greater element on its left. If there is no greater element on the left, it will never be removed.
  5.  
  6. We maintain a decreasing stack where each element is stored as (value, steps):
  7.  
  8. value = the element itself
  9. steps = number of steps after which this element will be removed
  10.  
  11. We process the array from left to right.
  12.  
  13. Take example: arr = [5, 3, 4]
  14.  
  15. First element 5: no element on the left, so it cannot be removed.
  16. Push (5, 0) → stack = [(5, 0)]
  17. Next element 3:
  18. We check the stack and remove elements ≤ 3. There are none.
  19. Now, stack still has (5, 0), which means 5 can remove 3.
  20. So, steps for 3 = 1.
  21. Push (3, 1) → stack = [(5, 0), (3, 1)]
  22.  
  23. Next element 4:
  24. We remove all elements ≤ 4. So (3, 1) is popped.
  25. While popping, we keep track of the maximum steps of removed elements. Here it is 1.
  26.  
  27. Now stack has (5, 0), so 5 can remove 4.
  28. But 4 can only be removed after 3 is removed, so it must wait.
  29. Hence, steps for 4 = max steps of popped elements (1) + 1 = 2.
  30.  
  31. Why do we take max steps of popped elements?
  32.  
  33. Because the current element must wait until all smaller elements in between are removed.
  34. Only then the greater element on the left can remove it.
  35. '''
  36.  
  37. import math
  38. class Solution:
  39.     def totalSteps(self, nums: List[int]) -> int:
  40.         st=[] #contains (value, steps to remove it)
  41.         ans=-math.inf
  42.         for i in nums:
  43.             steps=0
  44.             while len(st) and st[-1][0]<=i:
  45.                 steps=max(steps,st[-1][1])
  46.                 st.pop()
  47.             if len(st):
  48.                 steps+=1
  49.             else:
  50.                 steps=0
  51.             st.append([i,steps])
  52.             ans=max(ans,steps)
  53.         return ans
  54.  
  55.        
Add Comment
Please, Sign In to add comment