Tutorialspoint
Problem
Solution
Submissions

Container With Most Water

Certification: Intermediate Level Accuracy: 100% Submissions: 1 Points: 10

Write a JavaScript program to find two lines in an array that together with the x-axis forms a container that holds the most water. Given an array of non-negative integers where each integer represents the height of a line drawn at that position, find the maximum area of water that can be contained.

Example 1
  • Input: height = [1, 8, 6, 2, 5, 4, 8, 3, 7]
  • Output: 49
  • Explanation:
    • We have lines at positions 0,1,2,3,4,5,6,7,8 with heights [1,8,6,2,5,4,8,3,7].
    • The container is formed between position 1 (height=8) and position 8 (height=7).
    • The width is 8-1 = 7, and the height is min(8,7) = 7.
    • The area is 7 × 7 = 49, which is the maximum possible.
Example 2
  • Input: height = [1, 1]
  • Output: 1
  • Explanation:
    • We have two lines at positions 0 and 1, both with height 1.
    • The width between them is 1-0 = 1.
    • The height of water is min(1,1) = 1.
    • The area is 1 × 1 = 1.
Constraints
  • n == height.length
  • 2 ≤ n ≤ 10^5
  • 0 ≤ height[i] ≤ 10^4
  • Time Complexity: O(n)
  • Space Complexity: O(1)
ArraysDropboxTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use two pointers approach starting from both ends of the array
  • Calculate area using the formula: width × min(left_height, right_height)
  • Move the pointer with smaller height inward to potentially find larger area
  • Keep track of maximum area found so far
  • Continue until the two pointers meet

Steps to solve by this approach:

 Step 1: Initialize two pointers - left at start (index 0) and right at end (last index)
 Step 2: Initialize maxWater variable to store the maximum area found
 Step 3: While left pointer is less than right pointer, continue the loop
 Step 4: Calculate current width as (right - left) and height as min(height[left], height[right])
 Step 5: Calculate current area as width × height and update maxWater if larger
 Step 6: Move the pointer with smaller height inward (left++ or right--)
 Step 7: Return maxWater as the final result

Submitted Code :