单调栈
class Solution {
public int largestRectangleArea(int[] heights) {
//核心思想:以h[i]为高的矩形的宽等于i左右两边第一个小于h[i]之间的距离
//单调栈
int len = heights.length, area = 0;
Deque<Integer> st = new LinkedList<>();
//添加哨兵
int[] newHeight = new int[len+2];
for(int i = 0;i < len;i++){
newHeight[i+1] = heights[i];
}
newHeight[0] = 0;newHeight[len+1] = 0;
len += 2;
st.push(newHeight[0]);
for(int i = 0;i < len;i++){
while(newHeight[st.peek()] > newHeight[i]){//当栈顶元素比当前元素大时,说明以栈顶元素为高的矩形宽已经找到了
int height = newHeight[st.pop()];//出栈
int width = i - st.peek() - 1;
area = Math.max(area, height*width);
}
st.push(i);
}
return area;
//核心思想:以h[i]为高的矩形的宽等于i左右两边第一个小于h[i]之间的距离
//暴力法 超时
// int n = heights.length, ans = 0;
// for(int i = 0;i < n;i++){
// int minHeight = heights[i];
// int left = i, right = i;
// while(left-1 >= 0 && heights[left-1] >= minHeight)
// left--;
// while(right+1 < n && heights[right+1] >= minHeight)
// right++;
// ans = Math.max(ans, minHeight*(right - left + 1));
// }
// return ans;
}
}