-
解题思路:单调栈,以
i
位置为高度(宽),最长能有多长,其实就是找离i
最近的,小于i
的位置,其实就是单调栈 -
代码
class Solution: def largestRectangleArea(self, heights: List[int]) -> int: # 使用单调栈 栈底到栈顶 小到大 stack = [] ans = 0 n = len(heights) for i in range (n): while stack and heights[stack[-1]] > heights[i]: cur = stack.pop() R = i L = 0 if stack: L = stack[-1] + 1 ans = max(ans, (R - L) * heights[cur]) stack.append(i) while stack: cur = stack.pop() R = n L = 0 if stack: L = stack[-1] + 1 ans = max(ans, (R - L) * heights[cur]) return ans