-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathlargest_area_under_histogram.cpp
46 lines (35 loc) · 1.63 KB
/
largest_area_under_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
41
42
43
44
45
46
class Solution {
public:
int largestRectangleArea(vector<int>& heights) {
if(heights.size() == 0) return 0;
stack<int> indexes;
int largest_rectangular_area = INT_MIN;
int area_with_prev_top = 0;
int n = heights.size();
int i=0;
while(i<n) {
//for strictly increasing sequence of heights, keep inserting indexes of rectangles into the stack
if(indexes.empty() or heights[indexes.top()] <= heights[i]) {
indexes.push(i);
i++;
}
//found a decreasing sequence
else {
//get the previous top
int prev_top = indexes.top();
indexes.pop(); //remove the previous top
//calculate area that can be covered by current smaller rectangle.
area_with_prev_top = heights[prev_top] * (indexes.empty() ? i : i - indexes.top() - 1);
largest_rectangular_area = max(largest_rectangular_area, area_with_prev_top);
}
}
while(!indexes.empty()) {
int prev_top = indexes.top();
indexes.pop(); //remove the previous top
//calculate area that can be covered by current smaller rectangle.
area_with_prev_top = heights[prev_top] * (indexes.empty() ? i : i - indexes.top() - 1);
largest_rectangular_area = max(largest_rectangular_area, area_with_prev_top);
}
return largest_rectangular_area;
}
};