Question
Find two lines that together with the x-axis form a container, such that the container contains the most water. Return the maximum amount of water a container can store.
Steps
- Two pointers: start and end
- Choose the shorter height for area
- Move the pointer with shorter height
Python
class Solution:
def maxArea(self, height: List[int]) -> int:
start = 0
end = len(height) - 1
maxArea = 0
while start < end:
minHeight = min(height[start], height[end])
length = end - start
maxArea = max(maxArea, length * minHeight)
if height[start] > height[end]:
end -= 1
else:
start += 1
return maxArea
height =
[3,5,2,6,5,2]
Output = 15
Java
class Solution {
public int maxArea(int[] height) {
int maxArea = 0;
int left = 0;
int right = height.length - 1;
while (left < right) {
int minHeight = Math.min(height[left], height[right]);
int length = right - left;
maxArea = Math.max(maxArea, length * minHeight);
if (height[left] < height[right]) {
left += 1;
} else {
right -= 1;
}
}
return maxArea;
}
}
Top comments (0)