본문 바로가기
Beakjoon&프로그래머스/Java

[LeetCode/Java] Container With Most Water

by 현장 2026. 1. 1.

-Code

class Solution {
    public int maxArea(int[] height) {
        int left = 0, right = height.length - 1;
        int answer = 0;
        // 왼쪽이 오른쪽보다 작을 경우에만 반복
        while (left < right) {
            // 둘중 낮은 높이 구하기
            int minHeight = Math.min(height[left], height[right]);
            // 가로 넓기 구하기
            int with = right - left;
            // 가로, 세로 곱과 현재 저장 중인 값 중 큰 값 저장
            answer = Math.max(answer, with * minHeight);
            // left가 높으면 right - 1 반대면 left - 1
            if (height[left] > height[right]) {
                right--;
            } else {
                left++;
            }
        }

        return answer;
    }
}