forked from iamshubhamg/Leet-Code
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLargest Rectangle in Histogram.cpp
40 lines (40 loc) · 1.07 KB
/
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
//Problem Link : https://leetcode.com/problems/largest-rectangle-in-histogram/
class Solution {
public:
int largestRectangleArea(vector<int>& h) {
int n = (int)h.size();
int ans = 0;
stack<int> s;
for(int i=0;i< n;i++)
{
if(s.empty()) {s.push(i);continue;}
while(h[s.top()]>h[i])
{
int temp = s.top();
s.pop();
int area;
if(s.empty()){
area = h[temp]*i;
ans = max(ans,area);
break;
}
else {
area = h[temp]*(i-s.top()-1);
ans = max(ans,area);
}
}
s.push(i);
}
//i==n now
while(!s.empty())
{
int temp = s.top();
s.pop();
int area;
if(s.empty()) area = h[temp]*n;
else area = h[temp]*(n-s.top()-1);
ans = max(ans,area);
}
return ans;
}
};