【Golang】LeetCode 11. 盛最多水的容器

11. 盛最多水的容器

题目描述

思路

这道题的思路比较简单,我们使用双指针来进行解决。

初始时我们设置左右两个指针,令l, r := 0, len(height) - 1。

然后,我们开始对整个数组进行由两侧到中间的遍历,遍历的条件就是l < r。

在遍历之前我们设置ans := 0 用于记录最终的答案。

每一次遍历的过程中,我们计算一次当前容器所能盛水的最大容量,计算公式就是curr := min(height[l], height[r]) * (r - l)。

计算之后,我们对ans进行一次更新,即:ans = max(ans, curr)。

最后,比较关键的是l和r的移动策略。我们采用贪心的思路,每一次我们想要得到的答案实际上都是尽可能大的盛水容积,而较小的一侧的高度则是水容积计算的短板,因此我们比较当前height[l]和height[r]的大小关系,如果height[l] > height[r],则令r --,否则l ++。

基于以上思路,我们写代码来解决问题。

Golang 题解

go 复制代码
func maxArea(height []int) int {
    ans := 0
    l, r := 0, len(height) - 1
    for l < r {
        curr := min(height[l], height[r]) * (r - l)
        ans = max(ans, curr)
        if height[l] > height[r] {
            r --
        } else {
            l ++
        }
    }

    return ans
}

Python 题解

python 复制代码
class Solution:
    def maxArea(self, height: List[int]) -> int:
        ans, l, r = 0, 0, len(height) - 1
        while l < r:
            curr = min(height[l], height[r]) * (r - l)
            ans = max(ans, curr)

            if height[l] > height[r]:
                r -= 1
            else:
                l += 1
        return ans
相关推荐
一去不复返的通信er17 分钟前
力扣-图论-岛屿数量
算法·leetcode·图论
Xin7705 小时前
LeetCode 79. 单词搜索(DFS 回溯法)
leetcode
INGNIGHT8 小时前
440 · 背包问题(三)(无限次数)
算法·leetcode·动态规划
Tisfy10 小时前
LeetCode 3619.总价值可以被 K 整除的岛屿数目:广度优先搜索BFS
算法·leetcode·bfs·宽度优先
文丑颜不良啊12 小时前
LeetCode926~950题目解析
java·leetcode
alphaTao14 小时前
LeetCode 每日一题 2026/10/19-2026/10/25
算法·leetcode
Rain的Java大神之路15 小时前
面了 50 个候选人,90% 都挂在 LeetCode 3 无重复字符的最长子串:滑动窗口的 5 个致命坑
java·后端·leetcode
文丑颜不良啊1 天前
LeetCode876~900题目解析
java·leetcode
木井巳1 天前
【动态规划: 路径问题】不同路径
java·算法·leetcode·动态规划
晒太羊的猫2 天前
hot100子串
java·算法·leetcode