原题

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

思路

双指针

复杂度

时间:O(n)
空间:O(1)

Python代码

class Solution:
    def maxArea(self, height: List[int]) -> int:
        l, r = 0, len(height) - 1 
        ans = 0
        while l < r:
            w = r - l 
            h = min(height[l], height[r])
            area = w * h 
            ans = max(ans, area)
            if height[l] < height[r]:
                l += 1 
            else:
                r -= 1 
        return ans 

Go代码

func maxArea(height []int) int {
	l, r := 0, len(height)-1
	ans := 0
	for l < r {
		w := r - l
		h := min(height[l], height[r])
		area := w * h
		ans = max(ans, area)
		// 移动指针
		if height[l] < height[r] {
			l++
		} else {
			r--
		}
	}
	return ans
}
Logo

码道开发者社区,聚焦华为云码道 CodeArts 代码智能体,沉淀 Agent、Skill、鸿蒙开发实战内容,供开发者查阅资料、交流技术、分享工程实践

更多推荐