题目:最大的盛水容器
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.
原题链接地址:https://leetcode.com/problems/container-with-most-water/
分析:题意是给定长度为n整型数组height;分别构成(1,height[1]),(2,height[2]),….(n,height[n])坐标点,找出两个点分别过这些点做垂直X轴的垂线,以及连接这两个点,与X轴构成长方形容器,求该容器的最大值!
通过两个变量leftHeiht,rightHeight分别指向数组height的最左端和最右端,这样宽度最大,当缩小宽度,则需要寻找较大的高度。
做简单证明
Java 代码:(accepted)
public class ContainerWithMostWater {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { 1, 4, 5, 6, 3, 8, 9, 12, 45 };
System.out.println("Max Area is : " + maxArea(a));
int[] a1 = { 12,45,32,78,11,23,14 };
System.out.println("Max Area is : " + maxArea(a1));
int[] a2 = { 90,34,45,21,43,32};
System.out.println("Max Area is : " + maxArea(a2));
}
public static int maxArea(int[] height) {
int maxArea = 0; // The max area
int leftHight = 0;
int rigtHight = height.length - 1;
while (leftHight < rigtHight) {
//Calculate the max area
maxArea = Math.max(maxArea, (rigtHight - leftHight)
* Math.min(height[leftHight], height[rigtHight]));
//Because of cast effect, hence choose shortest height
if (height[leftHight] > height[rigtHight])
rigtHight--;
else
leftHight++;
//System.out.println("Left: " + height[leftHight] + " " + leftHight + " Right: " + height[rigtHight] + " " + rigtHight);
//System.out.println("Max Area: " + maxArea);
}
return maxArea;
}
}
测试结果:
Max Area is : 30
Max Area is : 92
Max Area is : 172
相关代码放在个人github:https://github.com/gannyee/LeetCode/tree/master/src