Given an array of different height
values, find the two "banks" that produce the most water valume.
Note that water will be limited by the lowest bank.
This is a two-pointer problem.
Pseudocode
Declare a left
and right
pointer, as well as a max
set to 0.
While left is less than right, check each height at both indices.
Find the lower bank, and multiply this lower bank's height by the distance between the left and right bank. This gives us our water volume.
Check if the water volume is more than what is currently set at max
, and save the higher number.
If the left bank is shorter than the right bank, increase left
so that we can search for a higher left bank. Else, decrease right
.
Return max
Code
var maxArea = function(height) {
let left = 0;
let right = height.length - 1;
let max = 0;
while (left < right) {
const leftBank = height[left];
const rightBank = height[right];
max = Math.max(max, Math.min(leftBank, rightBank) * (right - left));
if (leftBank < rightBank) {
left++;
} else {
right--;
}
}
return max;
};