Programming/LeetCode
[Dart] 11. Container With Most Water
Meezzi
2025. 5. 12. 09:35
728x90
1. 문제
2. 요구사항
1) 높이를 나타내는 양의 정수 배열 height가 주어진다.
2) 두 개의 막대를 선택해 만들어진 용기의 가장 큰 물 저장 용량을 구한다.
3) 용기는 막대의 높이와 그들 사이의 거리로 정의되며, 용량은 더 낮은 막대의 높이와 두 막대 사이의 거리를 곱한 값으로 계산된다.
3. 코드
class Solution {
int maxArea(List<int> height) {
// 투포인터를 활용하여 maxArea를 구한다.
int right = height.length - 1;
int left = 0;
int maxArea = 0;
// 두 포인터가 만나기 전까지 반복
while (left < right) {
int currentHeight = min(height[left], height[right]);
int currentArea = currentHeight * (right - left);
// 최대 면적 갱신
maxArea = max(maxArea, currentArea);
// 더 낮은 쪽 기둥을 안쪽으로 이동 (높은 면적을 만들기 위함)
if (height[right] > height[left]) {
left++;
} else {
right--;
}
}
return maxArea;
}
}728x90