Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- Logic:
- 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.
- We maintain a decreasing stack where each element is stored as (value, steps):
- value = the element itself
- steps = number of steps after which this element will be removed
- We process the array from left to right.
- Take example: arr = [5, 3, 4]
- First element 5: no element on the left, so it cannot be removed.
- Push (5, 0) → stack = [(5, 0)]
- Next element 3:
- We check the stack and remove elements ≤ 3. There are none.
- Now, stack still has (5, 0), which means 5 can remove 3.
- So, steps for 3 = 1.
- Push (3, 1) → stack = [(5, 0), (3, 1)]
- Next element 4:
- We remove all elements ≤ 4. So (3, 1) is popped.
- While popping, we keep track of the maximum steps of removed elements. Here it is 1.
- Now stack has (5, 0), so 5 can remove 4.
- But 4 can only be removed after 3 is removed, so it must wait.
- Hence, steps for 4 = max steps of popped elements (1) + 1 = 2.
- Why do we take max steps of popped elements?
- Because the current element must wait until all smaller elements in between are removed.
- Only then the greater element on the left can remove it.
- '''
- import math
- class Solution:
- def totalSteps(self, nums: List[int]) -> int:
- st=[] #contains (value, steps to remove it)
- ans=-math.inf
- for i in nums:
- steps=0
- while len(st) and st[-1][0]<=i:
- steps=max(steps,st[-1][1])
- st.pop()
- if len(st):
- steps+=1
- else:
- steps=0
- st.append([i,steps])
- ans=max(ans,steps)
- return ans
Add Comment
Please, Sign In to add comment