美文网首页
leetcode:盛最多水的容器

leetcode:盛最多水的容器

作者: 隔壁老王z | 来源:发表于2021-09-24 09:44 被阅读0次

给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
示例1:
输入:[1,8,6,2,5,4,8,3,7]
输出:49
解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。



示例 2:
输入:height = [4,3,2,1,4]
输出:16
示例 3:
输入:height = [1,1]
输出:1

解析:这是一道比较典型的双指针题,用两个标记从数组开头和末尾开始遍历,记录下最优解,淘汰掉较短的一方,直到两个标记相遇,遍历结束

function maxArea(height: number[]): number {
  let start = 0
  let end = height.length - 1
  let area = 0
  while (start <= end) {
    const temp = (end - start) * Math.min(height[start], height[end])
    area = Math.max(area, temp)
    if (height[start] < height[end]) {
      start += 1
    } else {
      end -= 1
    }
  }
  return area
};

相关文章

网友评论

      本文标题:leetcode:盛最多水的容器

      本文链接:https://www.haomeiwen.com/subject/sioagltx.html