Skip to main content

11.js

/** ------------------------------------------------------------------------------
*
* 11. Container With Most Water
* Topics: Array, Two Pointers, Greedy
* https://leetcode.com/problems/container-with-most-water/description/
*
------------------------------------------------------------------------------ */
/**
* @param {number[]} height
* @return {number}
*/
var maxArea = function (height) {
let left = 0
let right = height.length - 1
let max = 0

while (left < right) {
const h = Math.min(height[left], height[right])
max = Math.max(max, (right - left) * h)

if (height[left] < height[right]) {
const cur = height[left]
while (left < right && height[left] <= cur) left++
} else {
const cur = height[right]
while (left < right && height[right] <= cur) right--
}
}

return max
}

console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7])) // 49
console.log(maxArea([1, 1])) // 1