Cover image for LeetCode Hot 100 P84 Largest Rectangle in Histogram

LeetCode Hot 100 P84 Largest Rectangle in Histogram

Words 266
Views
Visitors

Timeline

Timeline

2026-03-18

init

Monotonic stack

Problem:

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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
#include <vector>#include <stack>using std::vector;using std::stack;class Solution {    public:        int largestRectangleArea(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]);                return max_area;        }};int main(){        vector<int> heights = { 2, 1, 5, 6, 2, 3 };        Solution S;        S.largestRectangleArea(heights);}
Loading comments…