11. Container With Most Water — Medium
前往題目
之前寫的文章
想法
- 雙指針
- 每次移動短的那邊
Greedy
思路
- 左右指針從
array
的開始與結尾 - 每個
area
都判斷一次是否大於maxArea
- 短的那邊移動,這樣才有機會取到更大的
- 直到左指針和右指針相撞結束
Code
class Solution {
public int maxArea(int[] height) {
int max = Integer.MIN_VALUE;
// 雙指針
int l = 0, r = height.length - 1;
// 直到距離只剩1
while (l < r) {
// 比較當前區域比較大還是之前的
max = Math.max(max, Math.min(height[l], height[r]) * (r - l));
// 哪邊小動哪邊
if (height[l] <= height[r]) {
++l;
} else {
--r;
}
}
return max;
}
}
11. Container With Most Water — Medium
https://f88083.github.io/2024/04/07/11-Container-With-Most-Water-—-Medium/