11. 盛最多水的容器

84 阅读1分钟

题目描述

leetcode-cn.com/problems/co…

分析

按照题目要求,找到两个 index,这两个 index 对应的柱子组成的水槽能放最多的水,也就是两者更矮的乘两者 index 差值求一个最多值

算法,数据结构

贪心,双指针

过程

不断移动两指针,在一开始设两指针为左右两边,最终找一个最大值

代码

/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function (height) {
  let left = 0,
    right = height.length - 1,
    max = 0

  while (left < right) {
    const w = right - left
    const h = height[left] < height[right] ? height[left++] : height[right--]
    max = Math.max(w * h, max)
  }

  return max
}