Java [leetcode 11] 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.

解题思路:

这道问题还是比较简单的,首先要理解它的意思,整个容器的高度是由较短的那根线决定的。然后从两边分别开始往中间收缩,对短的那根线进行往里收缩。这是容器的高度是由短的那根线决定的,那么当对高线往中间收缩时候,面积是在逐渐减小的,所以应该对矮的那根线进行收缩。

代码如下:

public class Solution {
    public int maxArea(int[] height) {
		int left = 0;
		int right = height.length - 1;
		int maxArea = (right - left) * Math.min(height[left], height[right]);
		int temp;
		
		while(left < right){
			if(height[left] < height[right]){
				left++;
			}
			else{
				right--;
			}
			temp = (right - left) * Math.min(height[left], height[right]);
			if(temp > maxArea)
				maxArea = temp;
		}
		return maxArea;
	}
}
原文地址:https://www.cnblogs.com/zihaowang/p/4456930.html