Last updated
Was this helpful?
Last updated
Was this helpful?
Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3]
.
The largest rectangle is shown in the shaded area, which has area = 10
unit.
Example:
给不同高度的histogram,问能形成的最大长方形面积。暴力法是对i,遍历其前面直到比它矮的,这段长度再乘以i的高即以i为底能形成的面积最大长方形;同理再遍历其后面,最后两段面积相加。也就是说想知道i前面有多少连续比它高的,而且这段元素在给i之后的作左边元素时高度都受限于h[i]。维护以高度为评判的递增序列,用stack,里头存index,当遇到高度比栈顶小的height[i]就弹出,计算它的index与i的距离 (宽, 因为这些元素都是比当前栈顶高的, 能以栈顶的高度形成面积), 再乘以它的高度即这个块能形成的最大面积。
时空复杂度O(n). 注意heights最后一个要是0, 确保能正确弹出所有元素. 还有int w = stack.isEmpty() ? i : (i - stack.peek() - 1)
https://leetcode.com/problems/largest-rectangle-in-histogram/description/