Skip to content

[leetcode] 11. Container With Most Water

Published: at 09:31 AM (2 min read)

Table of Contents

Open Table of Contents

Description

You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the line ithi^{th} are (i,0)(i, 0) and (i,height[i])(i, \text{height}[i]).

Find two lines, which, together with the xx-axis, forms a container, such that the container contains the most water.

Return the maximum area of the container.

Notice that you may not slant the container.

Example 1:

Example 1

Input: height = [1,8,6,2,5,4,8,3,7]
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.

Example 2:

Input: height = [1,1]
Output: 1

Constraints:

Approach

We can start with two pointers, one at the beginning and the other at the end of the array. We then calculate the area between the two pointers and update the maximum area if the current area is greater than the maximum area. Finally, we move the pointer with the smaller height towards the other pointer and repeat the process until the two pointers meet.

Solution

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function (height) {
  let maxArea = 0;

  // Use two pointers, one starting from the beginning (left) and one from the end (right) of the array.
  for (let left = 0, right = height.length - 1; left < right; ) {
    // Calculate the width between the two lines.
    let w = right - left;
    // Determine the height by finding the smaller of the two heights at the current pointers.
    let h = Math.min(height[left], height[right]);
    let area = w * h;

    if (area > maxArea) maxArea = area;

    // Move the pointer pointing to the shorter line inward, as this may increase the area.
    if (height[left] > height[right]) {
      right--;
    } else {
      left++;
    }
  }

  return maxArea;
};

Complexity Analysis

Time Complexity

The time complexity is O(n)O(n), where nn is the length of the height array. We only iterate through the array once.

Space Complexity

The space complexity is O(1)O(1) since we only use a constant amount of space.


Previous Post
[Mac] 如何使用 Apple Script 快速切換 Natural Scrolling 的滾動方向
Next Post
[CSS] 使用 aspect-ratio 讓你在嵌入 youtube, google map 等內容時做到 RWD