forked from sunstick/code-street
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontainer_with_most_water.cpp
More file actions
33 lines (27 loc) · 975 Bytes
/
container_with_most_water.cpp
File metadata and controls
33 lines (27 loc) · 975 Bytes
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
/*
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.
*/
class Solution {
public:
int maxArea(vector<int> &h) {
int res = -1;
int n = h.size();
int i = 0, j = n - 1;
while (i < j) {
res = max(res, (j - i) * min(h[i], h[j]));
if (h[i] <= h[j]) { // move i;
int newi = i + 1;
while (newi < j && h[newi] <= h[i])
newi++;
i = newi;
} else { // move j
int newj = j - 1;
while (i < newj && h[newj] <= h[j])
newj--;
j = newj;
}
}
return res;
}
};