-
[array] container with most waterAlgorithm/LeetCode 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; } }
'Algorithm > LeetCode' 카테고리의 다른 글
[array] 3sum closest (0) 2025.04.05 [stack] valid parentheses (0) 2025.03.23 [string] most common word (0) 2025.03.09 [string] reorder data in log files (0) 2025.03.09 [string] reverse string (0) 2025.03.08