码迷,mamicode.com
首页 > 其他好文 > 详细

Container With Most Water

时间:2015-06-06 07:56:30      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:

 

题目:

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.

 

题解:

这道题是先从两头开始算面积,面积的计算要由短板决定,并维护一个当前最大面积。

替换小的短板来计算面积。每一步只替换短板的原因是,短板决定面积,而高板不影响。

 

 1     public int maxArea(int[] height) 
 2     {
 3         if(height==null||height.length==0) return 0;
 4         int low=0;
 5         int high=height.length-1;
 6         int max=0;
 7         int area=0;
 8         while(low<high)
 9         {
10             area=(high-low)*Math.min(height[low],height[high]);
11             max=Math.max(max,area);
12             if(height[low]<height[high]) low++;
13             else high--;
14             
15         }
16         
17         return max;
18         
19     }

 

Container With Most Water

标签:

原文地址:http://www.cnblogs.com/hygeia/p/4555996.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!