-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlargest_rectangle_in_histogram.cpp
More file actions
67 lines (64 loc) · 1.93 KB
/
largest_rectangle_in_histogram.cpp
File metadata and controls
67 lines (64 loc) · 1.93 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
64
65
66
67
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
/**
* Describe: 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.
*/
class Solution {
public:
/**
* @param height: A list of integer
* @return: The area of largest rectangle in the histogram
*/
int largestRectangleArea(vector<int> &height) {
stack<pair<int, int>> record;
int max = 0;
int tmp;
int start = 0;
for (size_t i = 0; i < height.size(); i++) {
start = i;
// find the beginning position for the new element
// find the ending position for the element already in the stack
while (!record.empty() && record.top().second > height[i]) {
// set the beginning position with a lower value
start = record.top().first;
// calculate the ending of the element int the stact and
// get it's area
tmp = (i - record.top().first) * record.top().second;
max = max > tmp? max : tmp;
record.pop();
}
record.push(make_pair(start, height[i]));
}
// pop all element in the stack and get the value
while (!record.empty()) {
tmp = (height.size() - record.top().first) * record.top().second;
max = max > tmp? max : tmp;
record.pop();
}
return max;
}
};
/**
* Input: a number 'n' followed by n height of the bars
* Output: the max area
*/
int main() {
Solution so;
vector<int> test;
int n;
int tmp;
while (cin >> n) {
test.clear();
while (n-- > 0) {
cin >> tmp;
test.push_back(tmp);
}
int re = so.largestRectangleArea(test);
cout << "result: " << re << endl;
}
return 0;
}