26 March 2024
Medium
11. Container With Most Water
Link: https://leetcode.com/problems/container-with-most-water
Description: Given n
non-negative integers a1, a2, ..., an
, where each represents a point at coordinate (i, ai)
. n
vertical lines are drawn such that the two endpoints of the line i
are at (i, ai)
and (i, 0)
. Find two lines, which, together with the x-axis, form a container, such that the container contains the most water.
Solution:
Create two pointers, start
and end
, at the beginning and end of the array, respectively. Calculate the area between the two pointers and update the maximum area. Move the pointer with the smaller height inward to try to find a larger area. Continue this process until the pointers meet.
/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function (height) {
let start = 0
let end = height.length - 1
let max = 0
while (start < end) {
const current = Math.min(height[start], height[end]) * (end - start)
max = Math.max(max, current)
if (height[start] < height[end]) {
start++
} else {
end--
}
}
return max
}