-
Notifications
You must be signed in to change notification settings - Fork 0
/
leetcode084.cpp
90 lines (88 loc) · 2.11 KB
/
leetcode084.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
81
82
83
84
85
86
87
88
89
90
/*************************************************************************
> File Name: leetcode084.cpp
> Author:
> Mail:
> Created Time: Wed 31 Aug 2016 01:54:01 AM PDT
************************************************************************/
#include<iostream>
#include<vector>
using namespace std;
//方法一 穷举法
int largestRectangleArea(vector<int>& heights)
{
int max = 0 ;
//穷举右边界
for(int i = 0 ; i < heights.size();i++)
{
int area = 0;
//穷举左边界
for(int j = 0 ;j <= i;j++)
{
int min = heights[j];
//寻找左右边界之间的最小值
for(int k = j; k <= i;k++)
{
if(min > heights[k])
{
min = heights[k];
}
}
area = min *(i - j +1);
if(area > max)
{
max = area;
}
}
}
return max;
}
int largestRectangleArea_2(vector<int>& heights)
{
int max = 0;
//穷举左边界
for(int i = 0 ; i < heights.size() ; i++)
{
//寻找右边界
//当heights[i] > heights[i - 1]时候,选择heights[i]总会比
//heights[i-1]大
for(int j = i + 1; j < heights.size(); j++)
{
if(heights[j] < heights[j - 1])
{
i = j -1;
break;
}
else
{
i = j;
}
}
int min = heights[i];
int area = 0;
for(int j = i ; j >= 0 ;j--)
{
if(heights[j] < min)
{
min = heights[j];
}
area = min * (i - j + 1);
if(max < area)
{
max = area;
}
}
}
return max;
}
int main()
{
vector<int> heights;
heights.push_back(2);
heights.push_back(1);
heights.push_back(5);
heights.push_back(6);
heights.push_back(2);
heights.push_back(3);
cout << largestRectangleArea(heights) << endl;
cout << largestRectangleArea_2(heights) << endl;
}