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.
Java Solutions:
1.
public class Solution {
public int maxArea(int[] height) {
int areas=0;
int max_areas;
for(int i=0,j=height.length-1;j>i;){
max_areas=Math.min(height[i],height[j])*(j-i);
if(max_areas>areas)
areas=max_areas;
if(height[i]>height[j]){
j--;
}else{
i++;
}
}
return areas;
}
}
2. After Improvement :
public class Solution {
public int maxArea(int[] height) {
int areas=0;
int max_areas;
int hl=height[0];
int hr=height[height.length-1];
for(int i=0,j=height.length-1;j>i;){
max_areas=Math.min(hl,hr)*(j-i);
if(max_areas>areas)
areas=max_areas;
if(hl>hr){
while(i<j&&height[j]<=hr)
j--;
if(j>i)
hr=height[j];
}else{
while(i<j&&height[i]<=hl)
i++;
if(j>i)
hl=height[i];
}
}
return areas;
}
}