Overview
Given n non-negative integers representing wall heights where the width of each wall is 1, find two walls that together with the x-axis form a container that holds the most water.
Return the maximum amount of water the container can store.
Constraints
2 <= height.length <= 100,0000 <= height[i] <= 10,000- Must run in O(n) time.
- You may not slant the container.
Examples
maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]); // => 49 (walls at index 1 and 8: min(8,7) * 7 = 49)
maxArea([1, 1]); // => 1 maxArea([4, 3, 2, 1, 4]); // => 16 (walls at index 0 and 4: min(4,4) * 4 = 16)
Solution
Reveal solution
function maxArea(height) {
let left = 0, right = height.length - 1;
let max = 0;
while (left < right) {
const area = Math.min(height[left], height[right]) * (right - left);
max = Math.max(max, area);
if (height[left] < height[right]) left++;
else right--;
}
return max;
}Two pointers start at opposite ends. The area is limited by the shorter wall, so move the shorter pointer inward. O(n) time, O(1) space.
Resources
max-water-trapped.js
Maximum Water Trapped Between Walls
mediumcodingAlgorithmsTwo Pointers
Overview
Given n non-negative integers representing wall heights where the width of each wall is 1, find two walls that together with the x-axis form a container that holds the most water.
Return the maximum amount of water the container can store.
Constraints
2 <= height.length <= 100,0000 <= height[i] <= 10,000- Must run in O(n) time.
- You may not slant the container.
Examples
maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]); // => 49 (walls at index 1 and 8: min(8,7) * 7 = 49)
maxArea([1, 1]); // => 1 maxArea([4, 3, 2, 1, 4]); // => 16 (walls at index 0 and 4: min(4,4) * 4 = 16)
Solution
Reveal solution
function maxArea(height) {
let left = 0, right = height.length - 1;
let max = 0;
while (left < right) {
const area = Math.min(height[left], height[right]) * (right - left);
max = Math.max(max, area);
if (height[left] < height[right]) left++;
else right--;
}
return max;
}Two pointers start at opposite ends. The area is limited by the shorter wall, so move the shorter pointer inward. O(n) time, O(1) space.
Resources
NameTopicDifficulty
103 of 103 problems