https://leetcode.com/problems/container-with-most-water/description/
Container With Most Water - LeetCode
Can you solve this real interview question? Container With Most Water - You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that toget
leetcode.com
배열의 인덱스를 x좌표 값을 y좌표로 물이 들어있는 컨테이너를 만들 때 가장 많은 물 양을 담는 방법을 묻는 문제이다.
두 지점을 선택했을 때 가장 최선의 선택이 되는 경우를 찾는 방법이다.
두 인덱스의 차이는 컨테이너의 너비이며 높이는 두 값 중 더 낮은 값이 된다.
문제를 해결하기 위해 왼쪽 인덱스는 차례대로 증가 시켜 주었으며, 높이의 경우 우측 가장 끝부터 좌측 값보다 높은 경우를 찾아주었다. 좌측 값보다 높다면 사각형의 넓이는 좌측 좌표를 기준으로 최대의 높이인 좌측 높이 값이 될 것이며 우측 끝부터 감소 시키며 순환하기 때문에 너비 또한 좌측 값 기준 최대의 값이기 때문이다. 좌측 값을 끝까지 증가 시키며 순회하면 최선의 값이 나오게 된다.
public class Solution {
public int maxArea(int[] height) {
int answer = 0;
for(int i = 0; i < height.length - 1; i++){
for(int j = height.length - 1; j >= i + 1 ; j--){
int width = j - i;
if(height[i] < height[j]){
answer = Math.max(answer, width * height[i]);
break;
}else{
answer = Math.max(answer, width * height[j]);
}
}
}
return answer;
}
}
'Algolithm-Leetcode > Two Pointers' 카테고리의 다른 글
| Two Sum II - Input Array Is Sorted (0) | 2026.08.24 |
|---|---|
| Trapping Rain Water (0) | 2026.08.21 |
| 3Sum (0) | 2026.08.08 |
| Valid Palindrome (0) | 2026.07.21 |