Re: [閒聊] 每日leetcode

作者: dont   2024-10-10 09:41:15
962. Maximum Width Ramp
## 思路
先建個遞減的stack存index
再從後面掃回來(j) 檢查stack, 遇到<=的就pop並更新max width
Ex. [9,8,1,0,1,9,4,0,4,1]
stack = [0,1,2,3] # 9,8,1,0
max_width = 9 (num:1) - 2 (num:1) = 7
## Code
```python
class Solution:
def maxWidthRamp(self, nums: List[int]) -> int:
n = len(nums)
res = 0
stack = [0] # decreasing
for i in range(1, n):
if nums[stack[-1]] > nums[i]:
stack.append(i)
for j in range(n-1, -1, -1):
while stack and nums[stack[-1]] <= nums[j]:
res = max(res, j - stack.pop())
return res
```

Links booklink

Contact Us: admin [ a t ] ucptt.com