classSolution { public: intlargestRectangleArea(vector<int>& h){ //单调栈,枚举以每个柱子的高度为上边界,看左边界和右边界的情况,也是去看左边第一个比该柱子矮的柱子和右边第一个比这个柱子矮的柱子,这样就能求出对应的矩形的面积,然后找出一个全局最大即可。 int n = h.size(); vector<int> left(n), right(n); stack<int> stk;
for (int i = 0; i < n; i ++ ) { while (stk.size() && h[stk.top()] >= h[i]) stk.pop(); if (stk.empty()) left[i] = -1; else left[i] = stk.top(); stk.push(i); }
stk = stack<int>(); for (int i = n - 1; i >= 0; i -- ) { while (stk.size() && h[stk.top()] >= h[i]) stk.pop(); if (stk.empty()) right[i] = n; else right[i] = stk.top(); stk.push(i); }
int res = 0; for (int i = 0; i < n; i ++ ) { res = max(res, h[i] * (right[i] - left[i] - 1)); }