Skip to content

Instantly share code, notes, and snippets.

@ZhouYang1993
Created May 8, 2020 03:12
Show Gist options
  • Save ZhouYang1993/77f55938b75f22ad7567932e7c264284 to your computer and use it in GitHub Desktop.
Save ZhouYang1993/77f55938b75f22ad7567932e7c264284 to your computer and use it in GitHub Desktop.
Monotonic Stack
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
ret = 0
mono_stack = []
heights.append(0)
for i, v in enumerate(heights):
while mono_stack and heights[mono_stack[-1]] > v:
height = heights[mono_stack.pop()]
if mono_stack:
length = i - mono_stack[-1]-1
else:
length = i
ret = max(ret, height * length)
mono_stack.append(i)
return ret
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment