-
Notifications
You must be signed in to change notification settings - Fork 0
/
84_Largest_Rectangle_in_Histogram.cpp
70 lines (64 loc) · 1.7 KB
/
84_Largest_Rectangle_in_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
#include<bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> nextSmall(vector<int> arr, int n) {
vector<int> v(n);
stack<int> s;
s.push(-1);
for(int i = n-1; i >= 0; i--) {
while(true) {
int top = s.top();
int temp = arr[i];
if (top == -1 || arr[i] > arr[top]) {
v[i] = top;
break;
}
s.pop();
}
s.push(i);
}
return v;
}
vector<int> prevSmall(vector<int> arr, int n) {
vector<int> v(n);
stack<int> s;
s.push(-1);
for(int i = 0; i < n; i++) {
while(true) {
int top = s.top();
int temp = arr[i];
if (top == -1 || arr[i] > arr[top]) {
v[i] = top;
break;
}
s.pop();
}
s.push(i);
}
return v;
}
int largestRectangleArea(vector<int>& heights) {
int n = heights.size();
if(n == 0) return 0;
vector<int> next = nextSmall(heights, n);
vector<int> prev = prevSmall(heights, n);
if(next[0] == -1) next[0] = n;
int l = heights[0], b = next[0] - prev[0] - 1;
int maxArea = l * b;
for(int i = 1; i < n; i++) {
if(next[i] == -1) next[i] = n;
l = heights[i];
b = next[i] - prev[i] - 1;
maxArea = max(maxArea, l*b);
}
return maxArea;
}
};
int main() {
vector<int> arr = {2,1,5,6,2,3};
Solution s;
cout << s.largestRectangleArea(arr);
return 0;
return 0;
}