LeetCode 11. 盛最多水的容器
题目描述
思路分析
在每个状态下,无论长板或短板向中间收窄一格,都会导致水槽的底边宽度变短。
- 若向内移动短板,水槽的短板
min(h[i], h[j])
可能变大,因此下个水槽的面积可能增大。- 若向内移动长板,水槽的短板
min(h[i], h[j])
不变或变小,因此下个水槽的面积一定变小。
参考代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func maxArea(height []int) int {
left, right := 0, len(height)-1
res := 0
for left < right {
cur := min(height[left], height[right]) * (right - left)
res = max(res, cur)
if height[left] < height[right] {
left++ // 左边较小,向右移动左指针
} else {
right-- // 右边较小,向左移动右指针
}
}
return res
}
- 时间复杂度:O(n)
- 空间复杂度:O(1)
1
write your code here
CC BY-NC-SA 4.0
许可协议,转载请注明出处!
本博客所有文章除特别声明外,均采用