File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ // code link https://leetcode.com/problems/largest-rectangle-in-histogram/
2
+
3
+ #include < bits/stdc++.h>
4
+ using namespace std ;
5
+
6
+ // this problem demonstrates the best implementation of the stack
7
+ class Solution {
8
+ public:
9
+ int largestRectangleArea (vector<int >& height) {
10
+ int n=height.size ();
11
+ vector<int >right (n,n);
12
+ vector<int >left (n,-1 );
13
+ stack<int >st;
14
+ // for Next samllest right(NSR)
15
+ for (int i=0 ;i<n;i++){
16
+ while (!st.empty ()&& height[st.top ()]>height[i]){
17
+ right[st.top ()]=i;
18
+ st.pop ();
19
+ }
20
+ st.push (i);
21
+ }
22
+
23
+ // for Next smallest left(NSL)
24
+ for (int i=n-1 ;i>=0 ;i--){
25
+ while (!st.empty () && height[st.top ()]>height[i]){
26
+ left[st.top ()]=i;
27
+ st.pop ();
28
+ }
29
+ st.push (i);
30
+ }
31
+ int ans=0 ;
32
+ // maximum height for the given index is the (NSR-NSL-1)
33
+ for (int i=0 ;i<n;i++){
34
+ ans=max (ans,height[i]*(right[i]-left[i]-1 ));
35
+ }
36
+ return ans;
37
+ }
38
+
39
+ };
You can’t perform that action at this time.
0 commit comments