Leetcode 2289

Y Tech
Aug 14, 2023

Coding question asked in Meta and Amazon interviews.

'''
index 0, 1,2, 3, 4,5,6, 7
nums = [7,14,4,14,13,2,6,13]
res = [0, 1,0, 3, 2,0,0, 0] # res[i] = max(res[i]+1, res[prevIdx])

item: 7
stack: [14(3),14(1), 7(0) ]
'''
class Solution:
def totalSteps(self, nums: List[int]) -> int:
res = [0] * len(nums)
stack = [] # item in stack is (value, index)
for i in range(len(nums)-1, -1, -1):
num = nums[i]
while stack and stack[-1][0] < num:
_, idx = stack.pop()
res[i] = max(res[i]+1, res[idx])
stack.append((num, i))
return max(res)

--

--