You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container that holds the most water.
Return the maximum amount of water a container can store.
Example 1
Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: Lines 2 and 9 form a container of min(8,7)*7=49.
n == height.length2 <= n <= 10^50 <= height[i] <= 10^4Use two pointers from both ends. Move the pointer with the smaller height inward.
public int maxArea(int[] height) {
int left = 0, right = height.length - 1;
int maxWater = 0;
while (left < right) {
int h = Math.min(height[left], height[right]);
maxWater = Math.max(maxWater, h * (right - left));
// Move the shorter side — moving the taller side can only decrease area
if (height[left] < height[right]) left++;
else right--;
}
return maxWater;
}Time: O(n) · Space: O(1)