Algorithm/LeetCode
[array] container with most water
sw_develop
2025. 3. 22. 14:39
✅ Problem
https://leetcode.com/problems/container-with-most-water/description
✅ Approach & Solution
방식)
더보기
- 투 포인터 사용
- 포인터 이동 시 한칸 씩 이동할 필요없음, 최소 height보다 클 때까지 이동시킴
- 결과값이 커지려면 minHeight 값이 커져야 함 (right - left 는 포인터 이동할 때마다 무조건 작아지는 값이니까)
class Solution {
public int maxArea(int[] height) {
int maxArea = 0;
int left = 0;
int right = height.length - 1;
while (left < right) {
int minHeight = Math.min(height[left], height[right]);
maxArea = Math.max(maxArea, (right - left) * minHeight);
while (left < right && height[left] <= minHeight) {
left++;
}
while (left < right && height[right] <= minHeight) {
right--;
}
}
return maxArea;
}
}