Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
Created May 8, 2020 03:27
Show Gist options
  • Save ZhouYang1993/7daed727993254e78462658904bd0736 to your computer and use it in GitHub Desktop.
Save ZhouYang1993/7daed727993254e78462658904bd0736 to your computer and use it in GitHub Desktop.
Monotonic Stack
class Solution:
def trap(self, heights: List[int]) -> int:
stack = [] # a decreasing stack
total = 0
for i, v in enumerate(heights):
while stack and heights[stack[-1]] < v:
popped_idx = stack.pop()
if not stack:
break
height = min(heights[stack[-1]], v) - heights[popped_idx]
length = i - stack[-1] - 1
total += height * length
stack.append(i)
return total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment