-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargest_Rectangle_in_Histogram.cpp
More file actions
46 lines (42 loc) · 1.48 KB
/
Largest_Rectangle_in_Histogram.cpp
File metadata and controls
46 lines (42 loc) · 1.48 KB
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
/*
the stack, good job
don't worry, the lowest bar will take care of the final result
*/
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int n=height.size();
int y[n];
stack<int> stk;
for (int i = 0; i < n; i++) {
while (!stk.empty()) {
if (height[i] <= height[stk.top()]) stk.pop();
else break;
}
int j = (stk.empty()) ? -1 : stk.top();
// Calculating number of bars on the left
y[i] = i - j - 1;
stk.push(i);
}
while (!stk.empty()) stk.pop();
for (int i = n - 1; i > 0; i--) {
while (!stk.empty()) {
if (height[i] <= height[stk.top()]) stk.pop();
else break;
}
int j = (stk.empty()) ? n : stk.top();
// Calculating number of bars on the left + right
y[i] += (j - i - 1);
stk.push(i);
}
int res = 0;
for (int i = 0; i < n; i++) {
// Calculating height * width
y[i] = height[i] * (y[i] + 1);
if (y[i] > res) res = y[i];
}
return res;
}
};