Container With Most Water
Problem: Container With Most Water
We can use two pointers to solve this problem. One pointer points to the head and the other points to the tail. We first calculate the amount of water if we use the first and last as a container. Then we observe the containers one unit narrower. We can leave out the smaller one of the first and last number to get a bigger one-unit-narrower container. By this way, we can continue observing the container becoming more and more narrow and compare these candidates to get the answer.
Code in Python:
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
i, j, ans = 0, len(height)-1, 0
while i < j:
if height[i] <= height[j]:
if ans < height[i] * (j-i): ans = height[i] * (j-i)
i += 1
else:
if ans < height[j] * (j-i): ans = height[j] * (j-i)
j -= 1
return ans
Code in Java:
public class Solution {
public int maxArea(int[] height) {
int res = 0;
int l = 0, r = height.length-1;
while (l < r) {
res = Math.max(res, (r-l)*Math.min(height[l],height[r]));
if (height[l] < height[r]) {
l++;
} else {
r--;
}
}
return res;
}
}