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.
Solution
This is basically a more simplified version of Trapping Rain Water. Two pointers!
- When
height[l] == height[r]
, moving either pointer will reduce the width between the two pointers, which is a part of the area calculation. Since the height is determined by the shorter of the two lines, and both are equal at this point, moving either pointer will not immediately lead to a better solution. The decision to move either the left or the right pointer whenheight[l] == height[r]
is somewhat arbitrary in the context of this problem, so we could also doelif height[l] >= height[r]
to include the equal case.