-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlargestRectangleAreaInHistogram.cpp
More file actions
69 lines (51 loc) · 1.48 KB
/
largestRectangleAreaInHistogram.cpp
File metadata and controls
69 lines (51 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <iostream>
using namespace std;
int largeArea(vector<int>&histo) {
int n = histo.size();
int maxA = 0;
stack<int>st;
for(int i = 0; i <= n; i++) {
while(!st.empty() && (i==n || histo[st.top()] >= histo[i])) {
int height = histo[st.top()];
st.pop();
int width;
if(st.empty())width = i;
else width = i - st.top() - 1;
maxA = max(maxA, width*height);
}
st.push(i);
}
return maxA;
}
//Stack based solution to find the largest rectangle area in histogram
int largestRectangleArea(vector<int> &heights) {
int n = heights.size();
stack<int> stk;
int maxArea = INT_MIN;
for(int i = 0; i < n; i++) {
while(!stk.empty() && heights[stk.top()] > heights[i]) {
int element = stk.top(); stk.pop();
int nse = i;
int pse = stk.empty() ? -1 : stk.top();
maxArea = max(maxArea, heights[element]*(nse-pse-1));
}
stk.push(i);
}
while(!stk.empty()) {
int element = stk.top(); stk.pop();
int nse = n;
int pse = stk.empty() ? -1 : stk.top();
maxArea = max(maxArea, heights[element]*(nse-pse-1));
}
return maxArea;
}
int main() {
int n; cout << "Enter n : ";cin >> n;
vector<int>histo(n, 0);
for(int i = 0; i < n; i++) {
cout << "Enter element-"<<i<< " : ";cin >> histo[i];
}
cout << largeArea(histo) << endl;
cout << largestRectangleArea(histo) << endl;
return 0;
}