LeetCode - 11. Container With Most Water
Thoughts:
I choose two pointer to solve this problem, although this problem is not sorted array, but still need to compare the two values.
Thoughts visuzlization:
height = [1,8,6,2,5,4,8,3,7]
max = 0
l is left pointer, and r is right pointer
I can calculate the area by narrowing the width
and compare the heights
if height[l] is smaller than height[r], move left pointer to right
if height[r] is smaller than height[l], move right pointer to left
if same, narrow the width by moving both
why move both
if I move to the lower one, the area will be smaller
if I move to the higher one, I still need to use the other one that is equal as before, the area will be smaller too
result = (r - l) * Math.min(height[l], height[r])
and compare result with max value
[1,8,6,2,5,4,8,3,7]
l r
[1,8,6,2,5,4,8,3,7]
l r
[1,8,6,2,5,4,8,3,7]
l r
[1,8,6,2,5,4,8,3,7]
l r
[1,8,6,2,5,4,8,3,7]
l r
[1,8,6,2,5,4,8,3,7]
l r
[1,8,6,2,5,4,8,3,7]
l r
Code:
/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function (height) {
let l = 0;
let r = height.length - 1;
let max = (r - l) * Math.min(height[l], height[r]);
while (l < r) {
if (height[l] < height[r]) l++;
else if (height[l] > height[r]) r--;
else {
l++;
r--;
}
max = Math.max(max, (r - l) * Math.min(height[l], height[r]));
}
return max;
};
Reference
Copyright © 2024 | All rights reserved.