leetcode-11. 盛最多水的容器(双指针)

11. 盛最多水的容器
js 复制代码
/**
 * @param {number[]} height
 * @return {number}
 */
var maxArea = function (height) {
    // 时间复杂度 O(n)
    // 空间复杂度 O(1)
  let len = height.length;
  let left = 0,
    right = len - 1;
  let res = 0;

  while (left < right) {
    let area = Math.min(height[left], height[right]) * (right - left);
     res = Math.max(res, area);
    if (height[left] < height[right]) {
      left++;
    } else {
      right--;
    }
  }
  return res;
};

console.log(maxArea([1, 8, 6, 2, 5, 4, 8, 3, 7]));
py 复制代码
class Solution:
    def maxArea(self,height:List[int])->int:
        ans = 0
        left = 0
        right = len(height)-1
        while(left<right):
            area = (right-left)*min(height[left],height[right])
            ans = max(area,ans)
            if(height[left]<height[right]):
                left+=1
            else:
                right -=1
        return ans
reference

https://leetcode.cn/problems/container-with-most-water/

相关推荐
iceslime20 分钟前
旅行商问题(TSP)的 C++ 动态规划解法教学攻略
数据结构·c++·算法·算法设计与分析
aichitang20241 小时前
矩阵详解:从基础概念到实际应用
线性代数·算法·矩阵
OpenCSG2 小时前
电子行业AI赋能软件开发经典案例——某金融软件公司
人工智能·算法·金融·开源
chao_7893 小时前
链表题解——环形链表 II【LeetCode】
数据结构·leetcode·链表
dfsj660113 小时前
LLMs 系列科普文(14)
人工智能·深度学习·算法
薛定谔的算法3 小时前
《盗梦空间》与JavaScript中的递归
算法
kaiaaaa4 小时前
算法训练第十一天
数据结构·算法
?!7144 小时前
算法打卡第18天
c++·算法
springfe01014 小时前
构建大顶堆
前端·算法
天真小巫4 小时前
2025.6.8
职场和发展