-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLargestRectangleInHistogram.cpp
More file actions
53 lines (48 loc) · 1.52 KB
/
Copy pathLargestRectangleInHistogram.cpp
File metadata and controls
53 lines (48 loc) · 1.52 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
/**
Given n non-negative integers representing the histogram's bar height where the
width of each bar is 1, find the area of largest rectangle in the histogram.
Above is a histogram where width of each bar is 1, given height = [2,1,5,6,2,3].
The largest rectangle is shown in the shaded area, which has area = 10 unit.
For example,
Given height = [2,1,5,6,2,3],
return 10.
Solution: 1. Only calucate area when reaching local maximum value.
2. Keep a non-descending stack. O(n).
*/
//Naive solution
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int res = 0, N = height.size();
for (int i = 0; i < N; ++i) {
if (i < N-1 && height[i] <= height[i+1])
continue;
int minHeight = height[i];
for (int j = i; j >= 0; --j) {
minHeight = min(minHeight, height[j]);
res = max((i-j+1) * minHeight, res);
}
}
return res;
}
};
//better solution
class Solution {
public:
int largestRectangleArea(vector<int> &height) {
height.push_back(0);
int res = 0, i = 0, N = height.size();
stack<int> stk;
while (i < N)
{
if (stk.empty() || height[stk.top()] <= height[i])
stk.push(i++);
else {
int index = stk.top(); stk.pop();
int width = stk.empty() ? i : i - stk.top() - 1;
res = max(res, width * height[index]);
}
}
return res;
}
};