Fork me on GitHub

container-with-most-water

/**
* @author gentleKay
* 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.
*
* 给定n个非负整数a1,a2,…,an,其中每个表示一个坐标点(i,ai)。
* 画n条垂直线, {使线i的两个端点位于(i,ai)和(i,0)。(这句话可以不用看)}
* 找到两条线,与x轴一起构成一个容器,这样容器中的水就最多了。
* 注意:不要使容器倾斜。
*/

我个人觉得题目讲的不是很清楚,我查了一下,找到一张图。

这张图一看就很明了,让我们求得是,两条线之间的面积最大。

输入: [1,8,6,2,5,4,8,3,7]
输出: 49

图片的来源:https://blog.csdn.net/weixin_39364289/article/details/89146527

/**
 * @author gentleKay
 * 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.
 * 
 * 给定n个非负整数a1,a2,…,an,其中每个表示一个坐标点(i,ai)。
 * 画n条垂直线, {使线i的两个端点位于(i,ai)和(i,0)。(这句话可以不用看)}
 * 找到两条线,与x轴一起构成一个容器,这样容器中的水就最多了。
 * 注意:不要使容器倾斜。
 */

public class Main08 {

	public static void main(String[] args) {
		int[] height = {1,1};
		System.out.println(Main08.maxArea(height));
	}
	
	public static int maxArea(int[] height) {
		int start = 0;
		int end = height.length-1;
		int max = 0; int area = 0;
		while (start < end) {
			if (height[start] < height[end]) {
				area = (end - start) * height[start];
				start++;
			}else {
				area = (end - start) * height[end];
				end--;
			}
			if (area > max) {
				max = area;
			}
		}
        return max;
    }
}

  

posted @ 2019-07-24 15:09  gentleKay  阅读(132)  评论(0编辑  收藏  举报