-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontainer_with_most_water.cpp
51 lines (45 loc) · 1.43 KB
/
container_with_most_water.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
/**********************************
Given n non-negative integers a1, a2, ..., an, where each represents a point at
coordinate (i, ai). n vertical lines are drawn such that the two endpoints of
line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms
a container, such that the container contains the most water.
Note: You may not slant the container.
**********************************/
#include <vector>
using namespace std;
class Solution {
public:
int maxArea(vector<int> &height) {
int *next = new int[height.size()];
int left = 0;
for(int i = 1; i < height.size(); i++){
if(height[i] < height[i-1]){
for(int j = left; j < i; j++){
next[j] = i-1;
}
left = i;
}
}
for(int j = left; j < height.size(); j++){
next[j] = height.size()-1;
}
int res = 0;
left = 0;
for(int i = 0; i < height.size(); i++){
if(i > 0 && height[i] <= height[left]){
continue;
}
else{
left = i;
}
for(int j = next[i]; j < height.size(); j = next[j+1]){
res = max(res, (j-i)*min(height[i], height[j]));
if(j == height.size()-1){
break;
}
}
}
delete[] next;
return res;
}
};