The two pointers approach efficiently searches for the maximum area by starting with the widest possible container and gradually narrowing it:
This approach works due to the observation that the area is limited by the shorter line, so the only way to get a larger area is to find a taller line.
Time Complexity: O(n), where n is the number of elements in the height array, due to the single traversal of the array.
Space Complexity: O(1) as only a few extra variables are used.
1class Solution:
2 def maxArea(self, height):
3 left, right = 0, len(height) - 1
4 max_area = 0
5
6 while left < right:
7 h = min(height[left], height[right])
8 max_area = max(max_area, h * (right - left))
9
10 if height[left] < height[right]:
11 left += 1
12 else:
13 right -= 1
14
15 return max_area
16
17
18if __name__ == "__main__":
19 sol = Solution()
20 print(sol.maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]))
This Python solution efficiently finds the maximum water container area using the two-pointer technique. The while loop continues until the pointers meet, and the max_area is updated based on the minimum height between two pointers.
Although not optimal for large inputs, the brute force approach explores every possible pair of lines to find the maximum container area:
However, the complexity of this approach makes it unsuitable for large datasets due to its quadratic time complexity.
Time Complexity: O(n^2), where n is the number of elements as each pair is checked.
Space Complexity: O(1) due to a linear amount of extra space.
1function maxArea(height) {
2 let maxArea = 0;
3 for (let i = 0; i < height.length - 1; i++) {
4 for (let j = i + 1; j < height.length; j++) {
5 const h = Math.min(height[i], height[j]);
6 maxArea = Math.max(maxArea, h * (j - i));
7 }
8 }
9 return maxArea;
10}
11
12console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]));
This JavaScript brute force approach iterates over each potential pair of heights, assessing and recording the maximum container area possible.