P31 容纳最多水的凹槽容量
算法 20 阅读
信号摘要
难度:Medium · 时长:04:09 · leetcode 11 · lintcode 383
未对外公开播放权限
点击查看说明
描述
这个题目说的是,给你一个非负整数数组,数组中的数字表示高度值,在平面坐标画出来后,连同 X 轴一起,会形成许多的凹槽。你要找到两个高度值,使其形成的凹槽所能容纳的水最多。最后返回容纳的水量。
代码
public class AlgoCasts {
// Time: O(n), Space: O(1)
public int maxWater(int[] height) {
int max = 0;
int i = 0, j = height.length - 1;
while (i < j) {
int cur = Math.min(height[i], height[j]) * (j - i);
max = Math.max(max, cur);
if (height[i] < height[j]) ++i;
else --j;
}
return max;
}
}