Container With Most Water
HardAcc. 72.4%
+50 XP 25
The Reservoir Challenge
Imagine you are designing a water storage system. You have several vertical walls of different heights. Your goal is to find two walls that, together with the ground, can hold the maximum amount of water. The wider the gap and the taller the shorter wall, the more water you can store!
The Assignment
Your mission is to find the maximum volume. Your function receives an array of heights.
- Use two pointers:
leftat the very beginning andrightat the very end. - Calculate the area between them:
Width (right - left) * Height (shorter of the two walls). - Keep track of the maximum area found so far.
- Move the pointer pointing to the shorter wall inward (since moving the taller one can only decrease the area).
- Print the final maximum area.
01EXAMPLE 1
Input
[1, 8, 6, 2, 5, 4, 8, 3, 7]Output
49Explanation: Lines at index 1 and 8 (height 8 and 7) form area 7 * 7 = 49.
Constraints
- Solve in O(n) time.
- Solve in O(1) space.
ArraysTwo Pointers
JavaScriptSystem handles I/O — write your function only
Loading...
2 Hidden
Input Arguments
height[1,8,6,2,5,4,8,3,7]
Expected Output
49
Click RUN to test your solution