Skip to content

Commit a659557

Browse files
committed
container-with-most-water
1 parent 2d93a45 commit a659557

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/** ์ฒซ๋ฒˆ์งธ ํ’€์ด: ์žฌ๊ท€
2+
* ์‹œ๊ฐ„๋ณต์žก๋„: O(2^n)
3+
*/
4+
/**
5+
*
6+
var maxArea = function(height) {
7+
let maxWater = (height.length - 1) * Math.min(height[0], height[height.length-1]);
8+
function recursion(start, end){
9+
if(start >= end){
10+
// start์™€ end๊ฐ€ ๊ฐ™๊ฑฐ๋‚˜ start๊ฐ€ end๋ณด๋‹ค ์ปค์ง„ ๊ฒฝ์šฐ
11+
return;
12+
}
13+
maxWater = Math.max(maxWater, (end-start)*(Math.min(height[start], height[end])));
14+
recursion(start+1, end); // ์™ผ์ชฝ ๋Š˜๋ ค๋ณด๊ณ 
15+
recursion(start, end-1); // ์šฐ์ธก ๋Š˜๋ ค๋ณด๊ธฐ
16+
}
17+
recursion(0, height.length-1);
18+
return maxWater;
19+
};
20+
21+
/**
22+
* ๋‘๋ฒˆ์งธ ํ’€์ด: ํˆฌํฌ์ธํ„ฐ
23+
* ์‹œ๊ฐ„ ๋ณต์žก๋„: O(n)
24+
*/
25+
/**
26+
* @param {number[]} height
27+
* @return {number}
28+
*/
29+
var maxArea = function (height) {
30+
let left = 0;
31+
let right = height.length - 1;
32+
let maxWater = 0;
33+
34+
while (left < right) {
35+
// ํ˜„์žฌ ํฌ์ธํ„ฐ ์œ„์น˜์—์„œ ๋ฌผ์˜ ์–‘ ๊ณ„์‚ฐ
36+
const water = (right - left) * Math.min(height[left], height[right]);
37+
maxWater = Math.max(maxWater, water);
38+
39+
// ๋” ์ž‘์€ ๋†’์ด๋ฅผ ๊ฐ€์ง„ ์ชฝ์˜ ํฌ์ธํ„ฐ๋ฅผ ์ด๋™
40+
// ๋ฌผ์˜ ์–‘์€ ๋” ์ž‘์€ ๋†’์ด์— ์˜ํ•ด ์ œํ•œ๋˜๊ธฐ ๋•Œ๋ฌธ์— ์ž‘์€ ๋†’์ด๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋˜ ํฌ์ธํ„ฐ๋ฅผ ์ด๋™
41+
if (height[left] < height[right]) {
42+
left++;
43+
} else {
44+
right--;
45+
}
46+
}
47+
48+
return maxWater;
49+
};

0 commit comments

Comments
ย (0)