forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlargest_rectangle_area.cpp
61 lines (57 loc) · 1.57 KB
/
largest_rectangle_area.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
/**
*
*@gaurav yadav
Maintain a stack
a. If stack is empty heights[stack.top()] <= heights[i])
push this i into stack.
b. Else keep popooing from stack till value at i at top of stack is
less than value at current index.
c. While popping calculate area
if stack is empty
area = i * heights[top];
it means that till this point value just removed has to be smallest element
if stack is not empty
area = heights[top] * (i - stack.top() - 1);
* Finally return maxArea
* Time complexity is O(n)
* Space complexity is O(n)
*/
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
int area = 0;
int maxArea = 0;
stack <int> s;
int i;
for (i = 0; i < heights.size();) {
if (s.empty() || heights[s.top()] <= heights[i]) {
s.push(i++);
}
else {
int top = s.top();
s.pop();
if (s.empty()) {
area = i * heights[top];
}
else {
area = heights[top] * (i- s.top() -1);
}
if (area > maxArea)
maxArea = area;
}
}
while (!s.empty()) {
int top = s.top();
s.pop();
if (s.empty()) {
area = i * heights[top];
}
else {
area = heights[top] * (i- s.top() -1);
}
if (area > maxArea)
maxArea = area;
}
return maxArea;
}
};