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^4The brute force checks every pair of lines directly — O(n^2).
Start with the widest possible container (the two outermost lines) — width can only shrink from here, so it can only get better by improving the height.
Between the two current pointers, moving the TALLER one inward can never help — the container's height is capped by the SHORTER wall regardless, so only shrinking the shorter side has any chance of a bigger area.
public int maxAreaBruteForce(int[] height) {
int maxWater = 0;
for (int i = 0; i < height.length; i++) {
for (int j = i + 1; j < height.length; j++) {
int h = Math.min(height[i], height[j]);
maxWater = Math.max(maxWater, h * (j - i));
}
}
return maxWater;
}Time: O(n^2) · Space: O(1)