题解 | 盛水最多的容器
盛水最多的容器
https://www.nowcoder.com/practice/3d8d6a8e516e4633a2244d2934e5aa47
# # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param height int整型一维数组 # @return int整型 # class Solution: def maxArea(self , height: List[int]) -> int: n = len(height) # 当数组长度小于 2 时,不能形成容器,返回 0 if n < 2: return 0 # 初始化最大容量为 0 max_water = 0 # 左指针指向数组的第一个元素 left = 0 # 右指针指向数组的最后一个元素 right = n - 1 while left < right: # 计算当前容器的宽度 width = right - left # 计算当前容器的高度,取两个指针所指元素的较小值 current_height = min(height[left], height[right]) # 计算当前容器的容量 current_water = width * current_height # 更新最大容量 max_water = max(max_water, current_water) # 如果左指针所指元素较矮,将左指针右移一位 if height[left] < height[right]: left += 1 # 否则,将右指针左移一位 else: right -= 1 return max_water