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.
For example,
Given heights = [2,1,5,6,2,3]
,
return 10
.
题目链接:https://leetcode.com/problems/largest-rectangle-in-histogram/
题目分析:单调栈经典应用,如果问题是一个单调递增的,那很容易想到答案就是所有当前高度乘其之后个数的最大值,比如1 2 3答案就是max(1 * 3, 2 * 2, 3 * 1),为了可以达到这种状态,我们引入单调栈来维护,如果当前数字比栈顶小,那将数据出栈并更新大小再入栈,以下是利用单调栈对题目例子的求解过程。
1) 2入栈
2) 1入栈,1比2小,将2出栈并记录2带来的收益1*2=2,用1替代2入栈,此时栈中为1,1
3) 5入栈,此时栈中为1,1,5
4) 6入栈,此时栈中为1,1,5,6
5) 2入栈,2比6小,将6出栈并记录6带来的收益6*1=6,2比5小,将5出栈并记录5和6带来的收益5*2=10,用2代替5,6入栈,此时栈中为1,1,2,2,2
6) 3入栈,此时栈中为1,1,2,2,2,3
7) 单调栈数据插入完毕,一一出栈计算每个位置带来的收益与之前出栈的那些数字带来的收益取最大即可
public class Solution {
public int largestRectangleArea(int[] heights) {
int len = heights.length;
if(len == 0) {
return 0;
}
int ans = 0, cnt = 0;
Stack<Integer> stack = new Stack<>();
stack.push(heights[0]);
for (int i = 1; i < len; i++) {
if (stack.peek() <= heights[i]) {
stack.push(heights[i]);
}
else {
cnt = 0;
while (stack.size() > 0 && stack.peek() > heights[i]) {
cnt ++;
ans = Math.max(ans, cnt * stack.peek());
stack.pop();
}
while (cnt >= 0) {
stack.push(heights[i]);
cnt --;
}
}
}
cnt = 1;
while (stack.size() > 0) {
ans = Math.max(ans, stack.peek() * cnt);
cnt ++;
stack.pop();
}
return ans;
}
}
以上方法时间复杂度貌似不是O(n)的,直接将下标放入栈中,可以避免更新时频繁的出入栈操作,但是以下写法居然比上面的跑的还慢。。。谜。。。
public class Solution {
public int largestRectangleArea(int[] heights) {
int len = heights.length;
if(len == 0) {
return 0;
}
int[] h = new int[len + 1];
for(int i = 0; i < len; i ++) {
h[i] = heights[i];
}
h[len] = 0;
Stack<Integer> stk = new Stack<>();
int ans = 0, pos = 0, cur, w;
while(pos <= len) {
if(stk.empty() || h[pos] >= h[stk.peek()]) {
stk.push(pos ++);
}
else {
cur = stk.peek();
stk.pop();
w = stk.empty() ? pos : (pos - stk.peek() - 1);
ans = Math.max(ans, h[cur] * w);
}
}
return ans;
}
}