11 Container with most water
https://leetcode.com/problems/container-with-most-water/
class Solution {
public int maxArea(int[] height) {
int n = height.length;
int start = 0;
int end = n - 1;
int leftMax = 0;
int rightMax = 0;
int maxWater = 0;
while (start < end) {
leftMax = Math.max(leftMax, height[start]);
rightMax = Math.max(rightMax, height[end]);
maxWater = Math.max(maxWater, Math.min(leftMax, rightMax) * (end - start));
if (leftMax < rightMax) {
start++;
} else {
end--;
}
}
return maxWater;
}
}
喜欢知道解法之后就很好写的题
其实不需要维护leftmax和rightmax,只比较当前的左右值就行
class Solution {
public int maxArea(int[] height) {
int i = 0;
int j = height.length - 1;
int maxwater = 0;
while (i < j) {
int water = Math.min(height[i], height[j]) * (j-i);
maxwater = Math.max(water, maxwater);
if (height[i] < height[j]) {
//只有移动左指针才可能让短板变大
i++;
} else {
j--;
}
}
return maxwater;
}
}
Last updated