๊ฐ๋ฐ/๐ค ์๊ณ ๋ฆฌ์ฆ
[leetcode][Medium][Two Pointers] 11. Container With Most Water ํ์ด, ํด์ค (python)
ttoance
2023. 10. 29. 20:49
https://leetcode.com/problems/container-with-most-water/
1์ฐจ ํ์ด
์ผ๋จ ๋จ์ํ๊ฒ, O(n^2)๋ก ์ ๊ทผํ๋ค. ๊ทธ๋ฌ๋๋ ์๊ฐ ์ด๊ณผ๊ฐ ๋ฐ์ํ๋ค.
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
area = - sys.maxsize
# ์๊ฐ ์ด๊ณผ
area = - sys.maxsize
for l in range(len(height)):
for r in range(l + 1, len(height)):
area = max(area, (r - l) * min(height[l], height[r]))
return area
2์ฐจ ํ์ด
์๊ฐ ์ด๊ณผ๋ฅผ ๊ฐ์ ํ๊ณ ์, two-pointer ๋ฅผ ๋์ ํ๋ค.
๊ทธ๋ฐ๋ฐ, ํ์ l๊ณผ r ์ขํ๋ฅผ ์์ง์ด๋ ์กฐ๊ฑด์ด ๊ณ ๋ฏผ์ด ๋์๋ค.
l๊ณผ r ์ ์ฎ๊ธฐ๋ ๋ฐฉํฅ์ผ๋ก ๊ฐ๋ก ๊ธธ์ด๊ฐ ์ค์ด๋๋ ๋งํผ, ์ธ๋ก ๊ธธ์ด๊ฐ ๋์ ๋ฐฉํฅ์ผ๋ก ์์ง์ด๋ ๋ฐฉํฅ์ผ๋ก ์งํํ๋ค.
class Solution(object):
def maxArea(self, height):
"""
:type height: List[int]
:rtype: int
"""
l, r = 0, len(height) - 1
area = - sys.maxsize
while l < r :
area = max(area, (r - l) * min(height[l], height[r]))
# ๋์ด๊ฐ ํฐ์ชฝ์ผ๋ก ์ด๋
if height[l] < height[r]:
l = l + 1
else:
r = r - 1
return area
ํด์ค
https://www.youtube.com/watch?v=UuiTKBwPgAo
2์ฐจ ํ์ด์ ๋์ผํ ๋ฐฉ๋ฒ์ผ๋ก ํ์๋ค.
๋ฐ์ํ