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.
public class Solution {
public int maxArea(int[] height) {
int max = 0;
int i = 0;
int j = height.length - 1;
while (i < j) {
if (max < min(height[i], height[j]) * (j - i)) {
max = min(height[i], height[j]) * (j - i);
}
if (height[i] < height[j]) {
i++;
} else {
j--;
}
}
return max;
}
int min(int a, int b) {
if (a < b) return a;
return b;
}
}
本文介绍了一种寻找能盛最多水的两个垂直线的算法。该算法通过双指针技术,从两端向中间逼近,逐步缩小搜索范围,直到找到最优解。文章详细解释了算法的实现过程,并给出了具体的Java代码实现。
449

被折叠的 条评论
为什么被折叠?



