[M] 11. Container With Most Water

YJ·2025년 3월 27일

leetcode

목록 보기
20/100

https://leetcode.com/problems/container-with-most-water

문제

배열로 높이 주어지면 두 개 골라 젤 큰 직사각형

답안

public int maxArea(int[] height) {
	int left = 0;
	int right = height.length - 1;
	int maxArea = -1;
	while (left < right) {
		maxArea = Math.max(maxArea, calculateArea(height, left, right));
		if (height[left] > height[right]) {
			right--;
		}
		else {
			left++;
		}
	}
	return maxArea;
}

public int calculateArea(int[] height, int i, int j) {
    return (j - i) * Math.min(height[i], height[j]);
}

two pointer 로, 비교해서 더 짧은 쪽 pointer 를 이동시킨다.
왜?

  • 큰 쪽을 이동시켜봐야 작은 쪽 높이 때문에 현재 넓이보다 크게 만들 수 없다.
  • 작은 쪽을 이동하면 더 큰 수직선을 만날 가능성이 있다.

메모

profile
Hello

0개의 댓글