Container With Most Water
You're given an integer array height with n elements. Picture n vertical lines, where the ith line runs from (i, 0) up to (i, height[i]). Choose two of these lines so that, together with the x-axis between them, they form a container holding as much water as possible, and return that maximum volume.
Input Format
Implement maxArea(height). Inputs below show JavaScript function arguments; there is no stdin parsing.
Output Format
Return the result described in the statement.
Sample Input and Output
Example 1 ยท Run Sample
Input
height = [1,8,6,2,5,4,8,3,7] Output
49 Example 2
Input
height = [1,1] Output
1 Constraints
- 2 <= height.length <= 10^5
- 0 <= height[i] <= 10^4
Test Cases (2)
Case 1
Args: [[1,8,6,2,5,4,8,3,7]]
Expected: 49
Case 2
Args: [[1,1]]
Expected: 1
Topics
Use two pointers starting at the edges. Compute the area as the distance between pointers times the shorter line's height. Move the pointer pointing to the shorter line inward, since moving the taller one can never increase the area.
function maxArea(height) {
let left = 0, right = height.length - 1;
let max = 0;
while (left < right) {
const area = (right - left) * Math.min(height[left], height[right]);
max = Math.max(max, area);
if (height[left] < height[right]) left++;
else right--;
}
return max;
}Time: O(n) Space: O(1)
Saved in this browser only. Private to you.