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.length
2 <= n <= 105
0 <= height[i] <= 104
Solutions
Solution 1: Two Pointers
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)\).