Skip to content

Commit e6eb0d3

Browse files
committed
Container With Most Water Solution
1 parent 8b03d6a commit e6eb0d3

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* 두 선을 선택해 물을 담을 수 있는 최대 면적을 구하는 문제
3+
*
4+
* 가로 길이: 두 선 사이의 거리(인덱스 차이)
5+
* 세로 길이: 두 선 중 더 짧은 높이(물은 낮은 쪽으로 넘치기 때문)
6+
* 면적 = 가로 길이 × 세로 길이
7+
*
8+
* 양쪽 끝에서 시작하는 두 포인터를 사용
9+
* 투 포인터 방식이 효율적인 이유: 항상 더 작은 높이를 가진 쪽을 이동시키면 최대 면적을 놓치지 않기 때문
10+
* 더 큰 높이 쪽을 이동시키면 가로 길이는 줄어들고, 세로 길이는 같거나 더 작아져서 면적이 줄어들 수밖에 없음
11+
*
12+
* 시간 복잡도: O(n) - 배열을 한 번만 순회
13+
* 공간 복잡도: O(1) - 추가 공간 사용 없음
14+
*/
15+
/**
16+
* @param {number[]} height
17+
* @return {number}
18+
*/
19+
var maxArea = function (height) {
20+
let left = 0;
21+
let right = height.length - 1;
22+
let maxWater = 0;
23+
24+
while (left < right) {
25+
// 현재 두 선으로 만들 수 있는 물의 양 계산
26+
const width = right - left;
27+
const minHeight = Math.min(height[left], height[right]);
28+
const water = width * minHeight;
29+
30+
// 최대값 업데이트
31+
maxWater = Math.max(maxWater, water);
32+
33+
// 더 작은 높이를 가진 쪽의 포인터를 이동시킴
34+
if (height[left] < height[right]) {
35+
left++;
36+
} else {
37+
right--;
38+
}
39+
}
40+
41+
return maxWater;
42+
};

0 commit comments

Comments
 (0)