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.

  1. Use two pointers: left at the very beginning and right at the very end.
  2. Calculate the area between them: Width (right - left) * Height (shorter of the two walls).
  3. Keep track of the maximum area found so far.
  4. Move the pointer pointing to the shorter wall inward (since moving the taller one can only decrease the area).
  5. Print the final maximum area.

01EXAMPLE 1

Input[1, 8, 6, 2, 5, 4, 8, 3, 7]
Output49

Explanation: 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
JavaScript
Loading...
2 Hidden

Input Arguments

height[1,8,6,2,5,4,8,3,7]

Expected Output

49

Click RUN to test your solution