Commit 30a3ccc 1 parent ea3dfe4 commit 30a3ccc Copy full SHA for 30a3ccc
File tree 1 file changed +54
-0
lines changed
0084-largest-rectangle-in-histogram
1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public:
3
+ vector<int >findNextSmallToRight (vector<int >&arr)
4
+ {
5
+ int n=arr.size ();
6
+ vector<int >nextSmall (n);
7
+ stack<int >st;
8
+ for (int i=n-1 ;i>=0 ;i--)
9
+ {
10
+ while (!st.empty ()&&arr[st.top ()]>=arr[i])
11
+ {
12
+ st.pop ();
13
+ }
14
+ if (!st.empty ())
15
+ nextSmall[i]=st.top ();
16
+ else
17
+ nextSmall[i]=n;
18
+ st.push (i);
19
+ }
20
+ return nextSmall;
21
+ }
22
+ vector<int >findNextSmallToLeft (vector<int >&arr)
23
+ {
24
+ int n=arr.size ();
25
+ vector<int >nextSmall (n);
26
+ stack<int >st;
27
+ for (int i=0 ;i<n;i++)
28
+ {
29
+ while (!st.empty ()&&arr[st.top ()]>=arr[i])
30
+ {
31
+ st.pop ();
32
+ }
33
+ if (!st.empty ())
34
+ nextSmall[i]=st.top ();
35
+ else
36
+ nextSmall[i]=-1 ;
37
+ st.push (i);
38
+ }
39
+ return nextSmall;
40
+ }
41
+
42
+ int largestRectangleArea (vector<int >& heights) {
43
+ vector<int >nextSmallToLeft=findNextSmallToLeft (heights);
44
+ vector<int >nextSmallToRight=findNextSmallToRight (heights);
45
+ int largestRectangle=0 ;
46
+ for (int i=0 ;i<heights.size ();i++)
47
+ {
48
+ int length=nextSmallToRight[i]-nextSmallToLeft[i]-1 ;
49
+ cout<<length<<" \n " ;
50
+ largestRectangle=max (largestRectangle,length*heights[i]);
51
+ }
52
+ return largestRectangle;
53
+ }
54
+ };
You can’t perform that action at this time.
0 commit comments