代码随想录算法训练营第六十天 |84. 柱状图中最大的矩形
84. 柱状图中最大的矩形
题目链接:84. 柱状图中最大的矩形
- 暴力法
- 比接雨水难一些,但是可以相互转化
- 注意边界条件
-
class Solution { public: int largestRectangleArea(vector<int>& heights) { stack<int> st; heights.insert(heights.begin(), 0); // 数组头部加入元素0 heights.push_back(0); // 数组尾部加入元素0 int len = heights.size(); int res = 0; st.push(0); for(int i = 1; i < len; i++) { if(heights[i] > heights[st.top()]) { st.push(i); } else if (heights[i] == heights[st.top()]){ st.pop(); st.push(i); } else { while(heights[i] < heights[st.top()]){ int midIndex = st.top(); st.pop(); int leftIndex = st.top(); res = max(res, heights[midIndex] * (i - leftIndex - 1)); } st.push(i); } } return res; } };