Container with most water
Question
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.
Analysis
The amount of water that can be hold by a Container with two different heights of edge is determined by the smaller edge.
So we can use the idea of binary search to find the maximum volume of container that can be formed by the array.
start with left=0, right=len-1;
if arr[left]<arr[right], we increaese left index
else we decrease right index
Solution
public int maxArea(int[] height) {
if(height==null || height.length<2) return 0;
int lo=0,hi=height.length-1;
int result=0;
while(lo<hi){
result=Math.max(result,Math.min(height[lo],height[hi])*(hi-lo));
if(height[lo]<=height[hi]) lo++;
else hi--;
}
return result;
}