Why it works
- Start with the widest container: the two end walls. Every later one is narrower, so it can only win by being higher.
- Water rises only to the lower wall. Moving the higher wall is pointless: the width drops and the height cannot grow past the lower wall. So the lower wall moves.
- Each move drops a wall together with every container it could still make, and none of them beats the one just measured. So the best container is never skipped.
Complexity
Time O(n): each step moves one wall inwards, so there are at most n − 1 steps. Memory O(1): two pointers and the best area.
nextNow solve it yourself, no hints.
Solve on LeetCode ↗