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.
For example,
Given heights = [2,1,5,6,2,3],
return 10.
reference: https://www.youtube.com/watch?v=KkJrGxuQtYo
Solution:Stack
思路:
目的:找到每个柱的已自己为高度的左右边界。
左边界:就是此柱(的单调栈中的上一个柱),因为stack是增长的(单调栈)
右边界:当前未知,所以push进栈
方式:
(1)遇到增长的就将其index push至stack;
(2)遇到减的时候得到此柱上一个柱的右边界:此柱。则能计算上一个柱以其自身的max = (其右边界-左边界) * 其高度
Time Complexity: O(N) Space Complexity: O(N)
Solution Code:
class Solution {
public int largestRectangleArea(int[] heights) {
if(heights == null || heights.length == 0) return 0;
int max = 0;
Deque<Integer> stack = new ArrayDeque<>();
for(int cur = 0; cur < heights.length; cur++) {
// (1) 遇到增长的就将其index push至stack;
if(stack.isEmpty() || heights[cur] >= heights[stack.peek()]) {
stack.push(cur);
}
// (2) 遇到减的时候得到此柱上一个柱的右边界:此柱。
// 则能计算上一个柱以其自身的max = (其右边界-左边界) * 其高度
else {
int right_border = cur;
int index = stack.pop();
while(!stack.isEmpty() && heights[index] == heights[stack.peek()]) { // 等高情况
index = stack.pop();
}
int left_border = stack.isEmpty() ? -1 : stack.peek();
max = Math.max(max, (right_border - left_border - 1) * heights[index]);
cur--; // 重新从此柱
}
}
// 余下单调栈
int right_border = stack.peek() + 1;
while(!stack.isEmpty()) {
int index = stack.pop();
int left_border = stack.isEmpty() ? -1 : stack.peek();
max = Math.max(max, (right_border - left_border - 1) * heights[index]);
}
return max;
}
}