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/

相关推荐
Zedthm3 分钟前
LeetCode1004. 最大连续1的个数 III
java·算法·leetcode
神的孩子都在歌唱22 分钟前
3423. 循环数组中相邻元素的最大差值 — day97
java·数据结构·算法
YuTaoShao28 分钟前
【LeetCode 热题 100】73. 矩阵置零——(解法一)空间复杂度 O(M + N)
算法·leetcode·矩阵
dying_man1 小时前
LeetCode--42.接雨水
算法·leetcode
vortex52 小时前
算法设计与分析 知识总结
算法
艾莉丝努力练剑2 小时前
【C语言】学习过程教训与经验杂谈:思想准备、知识回顾(三)
c语言·开发语言·数据结构·学习·算法
ZZZS05162 小时前
stack栈练习
c++·笔记·学习·算法·动态规划
黑听人2 小时前
【力扣 困难 C】115. 不同的子序列
c语言·leetcode
hans汉斯3 小时前
【人工智能与机器人研究】基于力传感器坐标系预标定的重力补偿算法
人工智能·算法·机器人·信号处理·深度神经网络
vortex54 小时前
算法设计与分析:分治、动态规划与贪心算法的异同与选择
算法·贪心算法·动态规划