题目:
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.
翻译:一个数组的所有数字都是大于0的 ,求一对木板的高度,使得装水最多。 容积的短板高度*长度差
解题思路:分别从首尾开始遍历,并用MaxWater标志当前最大装水。如果前面指针指的高度小,则向后。如果后面指的小,则向前。
因为水的最多是短板高度乘以长度差。所以在手首尾指针相遇之前,得到的最大water就是所求。和前面的
代码:
public int maxArea(int[] height) { int left = 0; int right = height.length-1; int Maxwater = -1; while( left < right) { int water = Math.min(height[left],height[right])*(right - left); Maxwater = Math.max(Maxwater,water); if(height[left] < height[right]) left++; else right--; } return Maxwater; }
时间: 2024-10-05 04:18:57