File tree Expand file tree Collapse file tree
Stack/084.Largest-Rectangle-in-Histogram Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ class Solution {
2+ public:
3+ int largestRectangleArea (vector<int >& heights)
4+ {
5+ int n = heights.size ();
6+ stack<int >stk;
7+ vector<int >nextSmaller (n, n);
8+ for (int i=0 ; i<heights.size (); i++)
9+ {
10+ while (!stk.empty () && heights[stk.top ()] > heights[i])
11+ {
12+ nextSmaller[stk.top ()] = i;
13+ stk.pop ();
14+ }
15+ stk.push (i);
16+ }
17+
18+ while (!stk.empty ()) stk.pop ();
19+ vector<int >prevSmaller (n, -1 );
20+ for (int i=0 ; i<heights.size (); i++)
21+ {
22+ while (!stk.empty () && heights[stk.top ()] > heights[i])
23+ {
24+ stk.pop ();
25+ }
26+ if (!stk.empty ())
27+ prevSmaller[i] = stk.top ();
28+ stk.push (i);
29+ }
30+
31+ int ret = 0 ;
32+ for (int i=0 ; i<n; i++)
33+ ret = max (ret, heights[i]*(nextSmaller[i] - prevSmaller[i] - 1 ));
34+
35+ return ret;
36+ }
37+ };
You can’t perform that action at this time.
0 commit comments