力扣84.柱状图中最大的矩形
-
初始化pre_max 为-1 存距离最近的小于h[i]的元素下标
-
初始化suf_max 为 n 存距离最近的小于h[i]的元素下标
-
class Solution { public: int largestRectangleArea(vector<int>& heights) { int n = heights.size(); //分别初始化-1 和 n vector<int> pre_max(n,-1),suf_max(n,n); stack<int> st; for(int i=0;i<n;i++) { while(!st.empty() && heights[i] <= heights[st.top()]) st.pop(); if(!st.empty()) pre_max[i] = st.top(); st.push(i); } st = stack<int>(); for(int i=n-1;i>=0;i--) { while(!st.empty() && heights[i] <= heights[st.top()]) st.pop(); if(!st.empty()) suf_max[i] = st.top(); st.push(i); } int res=0; for(int i=0;i<n;i++) { res = max(res,(suf_max[i] - pre_max[i] - 1) * heights[i]); } return res; } };