This article is participating in the nuggets team number online activity, click to see the dachang spring recruiting positions

I. Title Description:

Give you n non-negative integers A1, A2… Each number represents a point in the coordinates (I, ai). Draw n vertical lines in the coordinates, and the two endpoints of vertical line I are (I, AI) and (I, 0). Find the two lines that together with the X-axis will hold the most water.

Note: You cannot tilt the container.

Example 1:

,8,6,2,5,4,8,3,7 input: [1] output: 49 explanation: the figure in the vertical line represents the input array,8,6,2,5,4,8,3,7 [1]. In this case, the maximum amount of water the container can hold (shown in blue) is 49.

Example 2:

Input: height = [1,1

The container that holds the most water

Ii. Analysis of Ideas:

  1. Define two Pointers to each end of the array, and then search in the middle,
  2. Each time I move, I’m going to take the larger value,
  3. The amount of water in the container = the smaller of the two edges times the distance between the two sides. Math.min(height[left], height[right]) * (right-left)

Iii. AC Code:

/ * * *@param {number[]} height
 * @return {number}* /
var maxArea = function(height) {
    let max = 0, left = 0, right = height.length-1;
    while(left <= right) {
        let area = Math.min(height[left], height[right]) * (right - left);
        max = Math.max(area, max);
        if(height[left] < height[right]) {
            left++;
        } else{ right--; }}return max;
};
Copy the code

Iv. Summary:

  • Time complexity: O(n)
  • Space complexity: O(1)