๊ฐœ๋ฐœ/๐Ÿค– ์•Œ๊ณ ๋ฆฌ์ฆ˜

[leetcode][Medium][Two Pointers] 11. Container With Most Water ํ’€์ด, ํ•ด์„ค (python)

ttoance 2023. 10. 29. 20:49

https://leetcode.com/problems/container-with-most-water/

 

Container With Most Water - LeetCode

Can you solve this real interview question? Container With Most Water - You are given an integer array height of length n. There are n vertical lines drawn such that the two endpoints of the ith line are (i, 0) and (i, height[i]). Find two lines that toget

leetcode.com

 

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์ฐจ ํ’€์ด์™€ ๋™์ผํ•œ ๋ฐฉ๋ฒ•์œผ๋กœ ํ’€์—ˆ๋‹ค. 

๋ฐ˜์‘ํ˜•