Leetcode 84. 柱状图中最大的矩形 单调栈
原题链接: Leetcode 84. 柱状图中最大的矩形
思路;
解法一: 枚举宽 暴力超时
当前宽度对应的最大面积的高度是: 遍历的最小高度
class Solution {
public:int largestRectangleArea(vector<int>& heights) {int res= 0;int n=heights.size();for(int i=0;i<n;i++){int h = INT_MAX;for(int j = i ;j<n;j++){h = min(h,heights[j]);res = max(res, (j-i+1)*h);}}return res;}
};
解法二: 枚举高 暴力超时
当前高度对应的最大面积的宽度是: 右边比他小的第一个 - 左边比它小的第一个 - 1
class Solution {
public:int largestRectangleArea(vector<int>& heights) {int res= 0;int n=heights.size();for(int i=0;i<n;i++){int l=i-1,r=i+1;int h=heights[i];while(l>=0 && heights[l]>=h) l--;while(r<n && heights[r]>=h) r++;res = max(res,(r-l-1)*h);}return res;}
};
解法三: 单调栈
参考: 暴力解法、栈(单调栈、哨兵技巧)
class Solution {
public:int largestRectangleArea(vector<int>& heights) {int res= 0;heights.push_back(0);stack<int> st;st.push(-1);st.push(0);int n=heights.size();for(int i=1;i<n;i++){if(!st.empty() && heights[i]>heights[st.top()]){st.push(i);}else{while(!st.empty() && st.top()!=-1 && heights[st.top()]>heights[i]){int h = heights[st.top()];st.pop();int l = st.top(),r = i;res = max(res,(r-l-1)*h);}st.push(i);}}return res;}
};