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/

相关推荐
MM_MS1 小时前
Halcon变量控制类型、数据类型转换、字符串格式化、元组操作
开发语言·人工智能·深度学习·算法·目标检测·计算机视觉·视觉检测
独自破碎E2 小时前
【二分法】寻找峰值
算法
mit6.8242 小时前
位运算|拆分贪心
算法
ghie90902 小时前
基于MATLAB的TLBO算法优化实现与改进
开发语言·算法·matlab
恋爱绝缘体12 小时前
2020重学C++重构你的C++知识体系
java·开发语言·c++·算法·junit
wuk9982 小时前
VSC优化算法MATLAB实现
开发语言·算法·matlab
Z1Jxxx3 小时前
加密算法加密算法
开发语言·c++·算法
乌萨奇也要立志学C++3 小时前
【洛谷】递归初阶 三道经典递归算法题(汉诺塔 / 占卜 DIY/FBI 树)详解
数据结构·c++·算法
vyuvyucd3 小时前
C++引用:高效编程的别名利器
算法
鱼跃鹰飞4 小时前
Leetcode1891:割绳子
数据结构·算法