11. Container With Most Water
Description
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, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
Example 1:
Input: height = [1,8,6,2,5,4,8,3,7] Output: 49 Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example 2:
Input: height = [1,1] Output: 1
Constraints:
n == height.length2 <= n <= 1050 <= height[i] <= 104
Solutions
Solution 1: Two Pointers
Thinking
The first idea is to try every pair \((i,j)\) and take \(\min(height[i],height[j])\times(j-i)\). Correct, but \(O(n^2)\). \(n \le 10^5\) will time out.
The bottleneck is treating every pair independently and ignoring that height is fixed by the shorter line. Start from the widest interval \([0,n-1]\): moving the taller end inward shrinks the width while the height is still capped by the shorter line, so the area cannot improve. We must drop the shorter line and look for a taller one.
So we shrink from both ends, always moving the shorter side. Each index is visited at most once.
We use two pointers \(l\) and \(r\) to point to the left and right ends of the array, respectively, i.e., \(l = 0\) and \(r = n - 1\), where \(n\) is the length of the array.
Next, we use a variable \(\textit{ans}\) to record the maximum capacity of the container, initially set to \(0\).
Then, we start a loop. In each iteration, we calculate the current capacity of the container, i.e., \(\textit{min}(height[l], height[r]) \times (r - l)\), and compare it with \(\textit{ans}\), assigning the larger value to \(\textit{ans}\). Then, we compare the values of \(height[l]\) and \(height[r]\). If \(\textit{height}[l] < \textit{height}[r]\), moving the \(r\) pointer will not improve the result because the height of the container is determined by the shorter vertical line, so we move the \(l\) pointer. Otherwise, we move the \(r\) pointer.
After the iteration, we return \(\textit{ans}\).
The time complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{height}\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | |
