Problem Description
Given an array height where each element represents the height of a vertical line on the x-axis, find two lines that, along with the x-axis, form a container holding the maximum amount of water.
Key Insights
- The container's area is determined by the distance between two lines multiplied by the shorter line's height.
- A brute-force approach checking all possible pairs would result in O(n^2) time complexity, which is inefficient for large inputs.
- A two-pointer approach allows us to solve the problem in O(n) time by initializing pointers at both ends and gradually moving them inward.
- By always moving the pointer corresponding to the shorter line, we are more likely to find a taller line that could potentially form a container with a larger capacity.
Space and Time Complexity
Time Complexity: O(n) - The algorithm makes a single pass through the array with two pointers. Space Complexity: O(1) - Only a few extra variables are used, regardless of the input size.
Solution
The optimal approach uses a two-pointer strategy:
- Start with two pointers at each end of the array.
- Calculate the area formed between the two lines at these pointers.
- Update the maximum area if the calculated value is larger.
- Move the pointer pointing to the shorter line inward, as this is the only possible way to potentially increase the height of the shorter line and thus the area.
- Continue until the two pointers meet.
This method effectively reduces the number of comparisons and ensures that every possible pair that can yield a larger area is considered.