-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargestest Histogram
45 lines (43 loc) · 1.06 KB
/
Largestest Histogram
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
class Solution {
public:
vector<int> ps(vector<int>& h) {
int n = h.size();
vector<int> p(n, -1);
stack<int> s;
for (int i = 0; i < n; i++) {
while (!s.empty() && h[s.top()] >= h[i]) {
s.pop();
}
if (!s.empty()) {
p[i] = s.top();
}
s.push(i);
}
return p;
}
vector<int> ns(vector<int>& h) {
int n = h.size();
vector<int> n_s(n, n);
stack<int> s;
for (int i = n - 1; i >= 0; i--) {
while (!s.empty() && h[s.top()] >= h[i]) {
s.pop();
}
if (!s.empty()) {
n_s[i] = s.top();
}
s.push(i);
}
return n_s;
}
int largestRectangleArea(vector<int>& h) {
int n = h.size();
vector<int> p = ps(h);
vector<int> n_s = ns(h);
int ar = 0;
for (int i = 0; i < n; i++) {
ar = max(ar, h[i] * (n_s[i] - p[i] - 1));
}
return ar;
}
};