-
Notifications
You must be signed in to change notification settings - Fork 1
/
092_Largest rectangle in a histogram.cpp
90 lines (64 loc) · 1.68 KB
/
092_Largest rectangle in a histogram.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Time Complexity -> O(N) + O(N) + O(N) + O(N) two passes
// Space Complexity -> O(3N)
#include<bits/stdc++.h>
int largestRectangle(vector < int > & heights) {
// Write your code here.
int n = heights.size();
vector<int> leftSmaller(n,-1);
vector<int> rightSmaller(n,-1);
stack<int> st;
for(int i = 0; i < n; ++i)
{
while(!st.empty() and heights[st.top()] >= heights[i])
st.pop();
if(st.empty())
leftSmaller[i] = 0;
else
leftSmaller[i] = st.top()+1;
st.push(i);
}
while(!st.empty())
st.pop();
for(int i = n-1; i >= 0; --i)
{
while(!st.empty() and heights[st.top()] >= heights[i])
st.pop();
if(st.empty())
rightSmaller[i] = n-1;
else
rightSmaller[i] = st.top()-1;
st.push(i);
}
int maxArea = 0;
for(int i = 0; i < n; ++i)
{
int width = (rightSmaller[i] - leftSmaller[i] + 1);
int area = width * heights[i];
maxArea = max(maxArea, area);
}
return maxArea;
}
// Time Complexity -> O(N) + O(N)
// Space Complexity -> O(N)
#include<bits/stdc++.h>
int largestRectangle(vector < int > & heights) {
// Write your code here.
int n = heights.size();
stack<int> st;
int maxArea = 0;
for(int i = 0; i <= n; ++i){
while(!st.empty() and (i == n or heights[st.top()] >= heights[i]))
{
int height = heights[st.top()];
st.pop();
int width;
if(st.empty())
width = i;
else
width = i - st.top() - 1;
maxArea = max(maxArea, height * width);
}
st.push(i);
}
return maxArea;
}