Let’s start by asking you to give you an array, each of which represents the height of the pool, and find the area between the two heights that holds the highest amount of water
Train of thought
1. Loop array, find out each area case and select the one with the largest area (but poor performance)
2. The two-pointer solution starts from the left and the right at the same time, and the one with the lower height gets closer to the middle first until it overlaps
var maxArea = function (height = [1.8.9.2.5.9.8.3.9]) {
// Left subscript is l and right subscript is r
let sum = 0; / / area
let max = 0; // Maximum area
let l = 0; / / left coordinates
let r = height.length - 1; / / right coordinates
while (l < r) {
// L starts from the first digit on the left,r starts from the first digit on the right, and each time the resulting area is stored in sum
sum = Math.min(height[l], height[r]) * (r - l);
// low l++ on the left and low r-- on the right
height[l] - height[r] < 0 ? l++ : r--;
// Find the maximum value of all results
max = Math.max(max, sum);
}
return max;
};
Copy the code