引用derrantcm的博客,网址:https://blog.csdn.net/derrantcm/article/details/46951851
package algorithm;
public class ContainMostWater {
//参考derrantcm的博客,网址:https://blog.csdn.net/derrantcm/article/details/46951851
//【011-ContainerWithMostWater(容纳最多的水)】
/*
原题
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.
题目大意
找两条竖线然后这两条线以及X轴构成的容器能容纳最多的水。
假设点(i,ai)、(j,aj)为最大容水值(2条垂线、和X轴),面积为:(j-i)*min(ai,aj).
如果选择ai与aj,此时面积最大。
则ai中左侧不会有比ai大的值,因如果有的话,即k,k<i且ak>ai,则(j-k)*min(ai,aj,ak)会对于选择的(i,ai),(j,aj)与实际不符。
同理(j,aj)右侧也不会有k>j,ak>aj。
*/
public static int solution(int[] height){
if(height==null||height.length<2){
return 0;
}
int left=0,right=height.length-1;
int result=0;
while(left<right){
result=Math.max(result, (right-left)*Math.min(height[left],height[right]));
if(height[left]<height[right]){
//左侧小于右侧。
int k=left;
//左侧向右添加,如果值小于height[left],则最大值一定为left,除非height[k]>height[left]才有可能
while(k<right&&height[k]<=height[left]){
k++;
}
left=k;
}else{
//左侧大于右侧,即height[left]>=height[right]
int k=right;
while(k>left&&height[k]<=height[right]){
k--;
}
right=k;
}
}
return result;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int length=4;
int[] array=new int[length];
array[0]=10;
array[1]=20;
array[2]=30;
array[3]=40;
int result=solution(array);
System.out.println("result="+result);
}
}