-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
40 lines (34 loc) · 931 Bytes
/
main.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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int maxArea(vector<int> &height)
{
int ans(0);
// Works but slow O(n^2)
// for (size_t i = 0; i < height.size(); i++)
// for (size_t j = i + 1; j < height.size(); j++)
// ans = max(ans, (int)(j - i) * min(height[j], height[i]));
size_t i = 0;
size_t j = height.size() - 1;
// Much faster O(n)
while (i >= 0 && j < height.size())
{
ans = max(ans, (int)(j - i) * min(height[j], height[i]));
if (height[i] < height[j])
i++;
else
j--;
}
return ans;
}
};
int main()
{
vector<int> height = {1, 8, 6, 2, 5, 4, 8, 3, 7};
Solution sol = Solution();
cout << sol.maxArea(height) << endl;
vector<int> height2 = {1, 1};
cout << sol.maxArea(height2) << endl;
}