
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.
- 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].
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.
- We have two lines at positions 0 and 1, both with height 1.
Constraints
- n == height.length
- 2 ≤ n ≤ 10^5
- 0 ≤ height[i] ≤ 10^4
- Time Complexity: O(n)
- Space Complexity: O(1)
Editorial
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. | ||||
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