-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargest Rectangle in a Histogram.cpp
More file actions
95 lines (75 loc) · 2.17 KB
/
Largest Rectangle in a Histogram.cpp
File metadata and controls
95 lines (75 loc) · 2.17 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
Maximum Rectangular Area/Largest Rectangle in a Histogram.cpp
Given an array representing height of bar in bar graph, find max histogram area in the bar graph. Max histogram
will be max rectangular area in the graph.
* Maintain a stack
* If stack is empty or value at index of stack is less than or equal to value at current index, push this into stack.
* Otherwise keep removing values from stack till value at index at top of stack is less than value at current index.
While removing value from stack calculate area
if stack is empty, it means that till this point value just removed has to be smallest element so area = ar[top] * I
if stack is not empty then this value at index top is less than or equal to everything from stack top + 1 till I. So
area will area = ar[top] * (I - S.top() - 1);
Finally maxArea is area if area is greater than maxArea.
Time complexity is O(n)
Space complexity is O(n)
*/
#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
#define NL '\n'
const int SIZE = 1e5;
int ar[SIZE];
stack<int> S;
int FindMaxRectangle(int n)
{
int I = 0, area = 0, maxArea = 0, top;
while (I < n)
{
// If this bar is higher than the bar on top stack, push it to stack.
if (S.empty() || ar[S.top()] <= ar[I])
{
S.push(I);
I++;
}
/*
If this bar is lower than top of stack, then calculate area of rectangle with stack top as the smallest
(or minimum height) bar. 'I' is 'right index' for the top and element before top in stack is 'left index'
*/
else
{
// store the top index
top = S.top();
S.pop();
if (S.empty())
area = ar[top] * I;
else
area = ar[top] * (I - S.top() - 1);
if (area > maxArea)
maxArea = area;
}
}
// Now pop the remaining bars from stack and calculate area with every popped bar as the smallest bar.
while (!S.empty())
{
// store the top index
top = S.top();
S.pop();
if (S.empty())
area = ar[top] * I;
else
area = ar[top] * (I - S.top() - 1);
if (area > maxArea)
maxArea = area;
}
return maxArea;
}
int main()
{
int tcases, I, J, K, N, n, m, cnt = 0, len;
cin >> n;
for (I = 0; I < n; I++)
cin >> ar[I];
cout << FindMaxRectangle(n) << NL;
return 0;
}