lc11-Container With Most Water

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 and n is at least 2.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int maxArea(vector<int>& height) {
int l = height.size();
int left = 0, right = l-1;
int mx = 0;
while (left<right) {
if (height[left]<height[right]) {
int tmp = height[left]*(right-left);
if (tmp>mx)
mx = tmp;
left++;
}
else {
int tmp = height[right]*(right-left);
if (tmp>mx)
mx = tmp;
right--;
}
}
return mx;
}
};