Skip to content

Commit c99f88a

Browse files
committed
Container With Most Water solution
1 parent 8472ed5 commit c99f88a

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/***
2+
*
3+
* @problem
4+
* - λ°°μ—΄μ—μ„œ 두 선을 μ„ νƒν•˜μ—¬ μ΅œλŒ€ 물을 담을 수 μžˆλŠ” 면적을 κ΅¬ν•˜λŠ” 문제
5+
*
6+
* @constraints
7+
* - λ°°μ—΄μ˜ κΈΈμ΄λŠ” 2 이상 10^5 μ΄ν•˜μž…λ‹ˆλ‹€.
8+
* - 각 λ†’μ΄λŠ” 0 이상 10^4 μ΄ν•˜μ˜ μ •μˆ˜μž…λ‹ˆλ‹€.
9+
*
10+
* @example
11+
* - μž…λ ₯: height = [1,8,6,2,5,4,8,3,7]
12+
* - 좜λ ₯: 49
13+
* (높이 8κ³Ό 7을 μ„ νƒν•˜μ—¬ 넓이 = min(8, 7) * (8 - 1) = 49)
14+
*
15+
* @description
16+
* - λ°°μ—΄μ˜ μ–‘ λμ—μ„œ μ‹œμž‘ν•˜λŠ” 두 개의 포인터λ₯Ό μ‚¬μš©ν•˜μ—¬ 문제λ₯Ό ν•΄κ²°ν•©λ‹ˆλ‹€.
17+
* - ν˜„μž¬ 포인터 μœ„μΉ˜μ—μ„œμ˜ 넓이λ₯Ό κ³„μ‚°ν•˜κ³  μ΅œλŒ€κ°’μ„ κ°±μ‹ ν•©λ‹ˆλ‹€.
18+
* - 더 μž‘μ€ 높이λ₯Ό κ°€μ§„ 포인터λ₯Ό μ΄λ™ν•˜μ—¬ 더 큰 넓이λ₯Ό νƒμƒ‰ν•©λ‹ˆλ‹€.
19+
*
20+
* @complexity
21+
* - μ‹œκ°„ λ³΅μž‘λ„: O(n)
22+
* (배열을 ν•œ 번만 μˆœνšŒν•˜λ©° μ΅œλŒ€ 넓이λ₯Ό 계산)
23+
* - 곡간 λ³΅μž‘λ„: O(1)
24+
* (μΆ”κ°€ λ©”λͺ¨λ¦¬ μ‚¬μš© 없이 ν¬μΈν„°λ§Œ μ‚¬μš©)
25+
*
26+
*/
27+
function maxArea(height: number[]): number {
28+
let left = 0, right = height.length - 1, maxArea = 0;
29+
30+
while (left < right) {
31+
// ν˜„μž¬ 넓이 계산 및 μ΅œλŒ€κ°’ κ°±μ‹ 
32+
maxArea = Math.max(maxArea, Math.min(height[left], height[right]) * (right - left));
33+
34+
// 더 μž‘μ€ λ†’μ΄μ˜ 포인터λ₯Ό 이동
35+
height[left] < height[right] ? left++ : right--;
36+
}
37+
38+
return maxArea;
39+
}

0 commit comments

Comments
Β (0)