You are given an integer array
heightof length . There are vertical lines drawn such that the two endpoints of the line are and .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.
Constraints:
- n == height.length
- 2 <= n <= 105
- 0 <= height[i] <= 104
Where would a good place be to start with this problem? The brute force solution would require us to check every combination of indices and finding the maximum volume that way. Instead, let’s start with just how water volume is calculated here. Let be the volume of water held by the container formed by the line at the th index and the th index, where
The equation gives us some clues on where to start: it is made of 2 parts, and .
Combined, our strategy takes shape: first start at the ends of the array, and continuously replace whichever line is shorter with the next line closer to the center, and repeat until the ends meet. We don’t have to check past that since the volume equation is symmetrical.
def maxArea(self, height: List[int]) -> int:
l, r = 0, len(height) - 1
max_vol = 0
while l < r:
volume = min(height[l], height[r]) * (r - l)
max_vol = max(max_vol, volume)
if height[l] < height[r]:
l += 1
else:
r -= 1
return max_vol
Let’s say . When we move to , we are essentially discarding all the pairs as not the optimal solution. How can we be so sure?
Consider one of those indices . First, notice that , so for to be the optimal solution we must have .
Either way, none of those indices can be the optimal solution, so we are safe to discard them.
Notice that l and r start at the ends of the array, and move towards each other one at a time. Since the while loop terminates when l >= r, the while loop iterates times. Each iteration is constant time, and since lines 1 and 2 as well as the return statement are constant time as well, the runtime complexity is in .
The only space used is to store l, r, max_vol, and volume, which are all constant integers—thus the space complexity is constant, in .