首页 > 代码库 > 【leetcode刷提笔记】Container With Most Water

【leetcode刷提笔记】Container With Most Water

Given n non-negative integers a1a2, ..., an, where each represents a point at coordinate (iai). n vertical lines are drawn such that the two endpoints of line i is at (iai) 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。


 

题解:分别设置两个游标start和end,start从height数组的前面往后面走,end从height数组的后面往前面走。每次计算当前start和end能够形成的container的最大面积,然后将height较小的游标移动(比如如果height[start]<height[end],那么就将start往后移动一步),直到两个游标相遇,算法结束。

算法的正确性:每次移动height较小的游标,保证了移动后不可能找到以height[游标]为高度的更大的container,因为宽度变小了。

代码如下:

 1 public class Solution { 2     public int maxArea(int[] height) { 3         int start = 0 ; 4         int end = height.length-1; 5         int maximum = 0; 6          7         while(start < end){ 8             int width = end - start; 9             int h = Math.min(height[start], height[end]);10             11             maximum = maximum > width*h?maximum:width*h;12             13             if(height[start] > height[end])14                 end--;15             else {16                 start++;17             }18         }19         20         return maximum;21     }22 }