容纳最多的水

引用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);
        
    }

}
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值