-
Notifications
You must be signed in to change notification settings - Fork 1
/
maxareainhistogram.cpp
80 lines (67 loc) · 2.02 KB
/
maxareainhistogram.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
// {"category": "Algorithm", "notes": "Find largest rectangle in histogram"}
#include <SDKDDKVer.h>
#include <stdio.h>
#include <tchar.h>
#include <iostream>
#include <vector>
#include <stack>
#include <Windows.h>
using namespace std;
//------------------------------------------------------------------------------
//
// 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.
//
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//
// Implementation
//
//------------------------------------------------------------------------------
int largestRectangleArea(vector<int> &height)
{
int area = 0;
int size = static_cast<int>(height.size());
int current = 0;
stack<int> offsets;
while (current < size || !offsets.empty())
{
if (offsets.empty() ||
current < size && height[offsets.top()] <= height[current])
{
offsets.push(current);
++current;
}
else
{
int previous = offsets.top();
offsets.pop();
int width = current;
if (!offsets.empty())
{
width = current - (offsets.top() + 1);
}
area = max(area, height[previous] * width);
}
}
return area;
}
//------------------------------------------------------------------------------
//
// Demo execution
//
//------------------------------------------------------------------------------
int _tmain(int argc, _TCHAR* argv[])
{
const int c_height[] = { 2, 1, 5, 6, 2, 3 };
vector<int> height;
for (int i = 0; i < ARRAYSIZE(c_height); i++)
{
height.push_back(c_height[i]);
}
int area = largestRectangleArea(height);
cout << "Largest rectangle area is " << area << endl;
cout << (area == 10 ? "PASS" : "FAIL") << endl;
return 0;
}