Largest Rectangle in Histogram #hard
Given an array of integers heights
representing the histogram’s bar height where the width of each bar is 1
, return the area of the largest rectangle in the histogram.
Example 1:
Input: heights = [2,1,5,6,2,3]
Output: 10
Explanation: The above is a histogram where width of each bar is 1.
The largest rectangle is shown in the red area, which has an area = 10 units.
Example 2:
Input: heights = [2,4]
Output: 4
Constraints:
-
1 <= heights.length <= 105
-
0 <= heights[i] <= 104
Solution:
Brute force
two pointers i, j; j keeps growing to the right. O(n^2)/O(1)
==divide and conquer==
O(nlogn)/==O(n)== recursion depth O(n)
最大的 rectangle 只能是:
当前最长 width * shortest height
shortest height 的左边里面接着找
shortest height 右边接着找
1 | class Solution { |
better divide and conquer uses Segment Tree
==### stack method==
==O(n)/O(n)==
做 increasing heights stack, 因为 heights 在里面是 increasing 的,如果出现 新的 height 比 stack top 小,则 heights[stack[j]..stack[k]] > new_height
,
==这些 heights 所能得到的 最大的 width 就已经确定了,可以计算这些 heights 能得到的 area 了==
注意这里
1 | class Solution { |