1. All-Pairs Area Enumeration (Brute Force)
Check every pair of vertical lines (i, j) with i < j and retain the maximum (j - i) * min(height[i], height[j]).
Nested loops evaluate n(n - 1) / 2 pairs.
Scalar loop indices and maxArea only.
How It Works
Exhaustive Pair Checking
Every candidate container is defined by a left index i and a right index j > i. Computing (j - i) * min(height[i], height[j]) over all n(n - 1) / 2 pairs guarantees finding the global optimum in O(1) space, but times out once n reaches 10^5.
Step-by-Step Dry Run
Best area paired with index 0 reaches width 8 * min(1, 7) = 8.
i = 0 -> maxWater = 8- +Trivial correctness without needing a pruning proof
- +Constant O(1) auxiliary space
- -Quadratic O(n²) runtime exceeds time limits at n = 10^5
Reference Implementation
Complete implementation for All-Pairs Area Enumeration (Brute Force) in Python, JavaScript, Java, C++, and C.
def max_area_brute(height: list[int]) -> int:best = 0n = len(height)for i in range(n):for j in range(i + 1, n):best = max(best, (j - i) * min(height[i], height[j]))return best
function maxAreaBrute(height) {
let best = 0;
for (let i = 0; i < height.length; i++) {
for (let j = i + 1; j < height.length; j++) {
best = Math.max(best, (j - i) * Math.min(height[i], height[j]));
}
}
return best;
}public class Solution {
public static int maxAreaBrute(int[] height) {
int best = 0;
for (int i = 0; i < height.length; i++) {
for (int j = i + 1; j < height.length; j++) {
best = Math.max(best, (j - i) * Math.min(height[i], height[j]));
}
}
return best;
}
}#include <vector>
#include <algorithm>
int maxAreaBrute(const std::vector<int>& height) {
int best = 0;
int n = static_cast<int>(height.size());
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
best = std::max(best, (j - i) * std::min(height[i], height[j]));
}
}
return best;
}int maxAreaBrute(const int* height, int n) {
int best = 0;
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int h = height[i] < height[j] ? height[i] : height[j];
int area = (j - i) * h;
if (area > best) best = area;
}
}
return best;
}