Container With Most Water

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 and n is at least 2.

Container With Most Water_第1张图片

解题思路:动态规划解决。利用两个指针分别指向最左边和最右边,计算容量为Math.min(height[left], height[right])*(right-left); 每次将较小的往中间移动,如第一次比较第左边和第右边的高度,发现左边的更小,因此将左边的指针往右边移动。每次计算后与目前的最大值max进行比较并取大者。直到两个指针相遇结束运算。

class Solution {
    public int maxArea(int[] height) {
     int left=0;
     int right=height.length-1;
     int max=0;
     int temp;
     while(left!=right)
     {
    	 temp=Math.min(height[left], height[right])*(right-left);
    	 if(temp>max)
    		 max=temp;
    	 if(height[left]>height[right])
    		 right--;
    	 else
    		 left++;
     }
     return max;
    }
}

 

结果:

Container With Most Water_第2张图片

你可能感兴趣的:(【LeetCode】)