Skip to content

Commit eefe910

Browse files
committed
Solution: Container with Most Water
1 parent 96f433c commit eefe910

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* ํ’€์ด
3+
* - container์˜ ๋ฐ‘๋ณ€์ด ๋„“๊ณ  ๋†’์ด๊ฐ€ ๋†’์„ ์ˆ˜๋ก ์ €์žฅํ•˜๋Š” ๋ฌผ์˜ ์–‘์ด ๋งŽ์Šต๋‹ˆ๋‹ค
4+
* - ๋”ฐ๋ผ์„œ ๋ฐ‘๋ณ€์ด ๊ฐ€์žฅ ๋„“์€ container๋ถ€ํ„ฐ ํƒ์ƒ‰ํ•˜๋ฉด ํƒ์ƒ‰ ํšจ์œจ์„ ๋†’์ผ ์ˆ˜ ์žˆ๋‹ค๋Š” ์ƒ๊ฐ์„ ํ–ˆ์Šต๋‹ˆ๋‹ค
5+
* - ์–‘ ๋์—์„œ๋ถ€ two pointer๋ฅผ ์ด์šฉํ•˜์—ฌ ํƒ์ƒ‰์„ ์‹œ์ž‘ํ•ฉ๋‹ˆ๋‹ค
6+
* - lo, hi ์ค‘์—์„œ ๋†’์ด๊ฐ€ ๋” ๋‚ฎ์€ pointer๋ฅผ ์•ˆ์ชฝ์œผ๋กœ ์ด๋™์‹œํ‚ต๋‹ˆ๋‹ค
7+
* - ์™œ๋ƒํ•˜๋ฉด ๋†’์ด๊ฐ€ ๋” ๋‚ฎ์€ pointer๋ฅผ ์ด๋™์‹œ์ผฐ์„ ๋•Œ ๊ธฐ์กด container๋ณด๋‹ค ๋” ๋†’์ด๊ฐ€ ๋†’์€ container๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฐ€๋Šฅ์„ฑ์ด ์ƒ๊ธฐ๊ธฐ ๋•Œ๋ฌธ์ž…๋‹ˆ๋‹ค
8+
*
9+
* Big O
10+
* - N: ์ฃผ์–ด์ง„ ๋ฐฐ์—ด height์˜ ํฌ๊ธฐ
11+
*
12+
* - Time complexity: O(N)
13+
* - ๋ฐฐ์—ด height๋ฅผ ์กฐํšŒํ•˜๋ฏ€๋กœ ์ „์ฒด ์‹คํ–‰์‹œ๊ฐ„ ๋˜ํ•œ N์— ๋น„๋ก€ํ•˜์—ฌ ์„ ํ˜•์ ์œผ๋กœ ์ฆ๊ฐ€ํ•ฉ๋‹ˆ๋‹ค
14+
*
15+
* - Space complexity: O(1)
16+
*/
17+
18+
class Solution {
19+
public:
20+
int maxArea(vector<int>& height) {
21+
int n = height.size();
22+
int lo = 0;
23+
int hi = n - 1;
24+
25+
int res = 0;
26+
while (lo < hi) {
27+
int w = hi - lo;
28+
int h = min(height[lo], height[hi]);
29+
30+
res = max(res, w * h);
31+
32+
if (height[lo] > height[hi]) {
33+
--hi;
34+
} else {
35+
++lo;
36+
}
37+
}
38+
39+
return res;
40+
}
41+
};

0 commit comments

Comments
ย (0)