OK, I couldn’t figure this one out on my own. After struggling on and off, I eventually gave in and looked at other people’s approaches.
Let me share my thought process.
The first idea was brute force: pick every pair of lines, calculate the volume, and find the maximum.
The logic is correct, but it timed out. I checked the test cases – the data set is quite large.
So what next? We clearly need an approach with complexity lower than $O(n^2)$ to pass.
I thought for a long time. Sorting? Filling water from bottom up? Two pointers, one on each side, moving inward? Or fix the left side and assume the other line is always to the right?
It was all over the place.
Finally I looked at someone else’s solution, and it’s really so easy – I can’t believe I didn’t think of it. Sigh.
The approach is simple: greedy.
Two pointers, one on each end. Record the volume. Move the pointer at the shorter line inward. People online call this the “two-pointer” technique.
During implementation, when the two lines are equal in height, you could move either the left or the right pointer. So the best approach is to use recursion to handle both cases.
Here’s the code. Solving problems can be quite painful, especially for someone slow like me. Keep going!
| |