forked from piyush-kash/Hacktober2021-cpp-py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxAreaHistogram.cpp
More file actions
63 lines (47 loc) · 1.4 KB
/
maxAreaHistogram.cpp
File metadata and controls
63 lines (47 loc) · 1.4 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
#include <bits/stdc++.h>
using namespace std;
int main()
{
int a[] = {6, 2, 5, 4, 5, 1, 6};
int n = sizeof(a) / sizeof(a[0]);
//we have to find max area of rectangle in hiostogram (pepcoding vid)
//for solving we will have to find the nearest shorter element to the curr element on both side
//as if side elements are greater than curr, then they would contribute in rectangle but the width will stop as soon as
// we encounter shorter height on both sides
stack<int> s;
s.push(n - 1);
int rb[n]; // next shorter element on right
rb[n - 1] = n - 1;
for (int i = n - 2; i >= 0; i--)
{
while (s.size() > 0 && a[i] < a[s.top()])
s.pop();
if (s.size() == 0)
rb[i] = n;
else
rb[i] = s.top();
s.push(i);
}
int lb[n]; //next shorter element on left
lb[0] = -1;
for (int i = 1; i < n; i++)
{
while (s.size() > 0 && a[i] < a[s.top()])
s.pop();
if (s.size() == 0)
lb[i] = -1;
else
lb[i] = s.top();
s.push(i);
}
int maxArea = 0;
for (int i = 0; i < n; i++)
{
int width = rb[i] - lb[i] - 1;
int h = a[i];
int currArea = h * width;
if (currArea > maxArea)
maxArea = currArea;
}
cout << maxArea;
}