[LeetCode][11. Container With Most Water] 2 Approaches: Brute Force and Two Pointers with Image Explanation
By Long Luo
This article is the solution 2 Approaches: Brute Force and Two Pointers with Image Explanation of Problem 11. Container With Most Water .
Here shows 2 Approaches to slove this problem: Brute Force and Two Pointers.
Intuition

Suppose two pointers \(i\), \(j\), the heights of the vertical lines are \(h[i]\), \(h[j]\), and the area in this state is \(S(i, j)\).
As we all known, the container is determined by the short line, the area formula can be easily obtained:
\[ S(i, j) = min(h[i], h[j]) \times (j - i) \]
Brute Froce
It’s easy to use the brute force approach, the total states is \(C(n, 2)= n \times (n - 1) / 2\), we have to enumerate all these states to get the max area.
The time complexity is \(O(n^2)\), exceed the time limit.1
2
3
4
5
6
7
8
9
10
11
12
13
14// BF time: O(n^2) space: O(1)
// TimeOut
public static int maxArea_bf(int[] height) {
int len = height.length;
int max = 0;
for (int i = 0; i < len - 1; i++) {
for (int j = i + 1; j < len; j++) {
int area = Math.min(height[i], height[j]) * (j - i);
max = Math.max(max, area);
}
}
return max;
}
Analysis
- Time Complexity: \(O(n^2)\)
- Space Complexity: \(O(1)\)