This case is a classic monotonic stack scenario. Think carefully about this problem: it’s essentially about finding the first rectangle to the left that is lower than itself, and the first rectangle to the right that is lower than itself. In fact, this is the classic ‘Next Greater’ problem.
#include<vector> #include<stack> using std::vector; using std::stack;
classSolution { public: intlargestRectangleArea(vector<int> &heights) { int i, n = heights.size(), max_area = 0; vector<int> left(n, 0); vector<int> right(n, n - 1); stack<int> stk1, stk2;
for (i = 0; i < n; i++) { while (!stk1.empty() && heights[i] < heights[stk1.top()]) { right[stk1.top()] = i - 1; // right boundary stk1.pop(); } stk1.push(i); }
// while (!stk.empty()) { // right[stk.top()] = n - 1; // }
for (i = n - 1; i >= 0; i--) { while (!stk2.empty() && heights[i] < heights[stk2.top()]) { left[stk2.top()] = i + 1; // left boundary stk2.pop(); } stk2.push(i); }
// while (!stk.empty()) { // left[stk.top()] = 0; // }
for (i = 0; i < n; i++) max_area = std::max(max_area, (right[i] - left[i] + 1) * heights[i]);