반응형
problem: https://leetcode.com/problems/container-with-most-water/
code:
brute-force
time limit exceeded
class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height)-1
result = 0
while(left<right):
if height[left] < height[right]:
code:
better solution
O(n)
class Solution:
def maxArea(self, height: List[int]) -> int:
left = 0
right = len(height)-1
maxWater = 0
while left < right :
# get water
water = (right-left)*min(height[left],height[right])
# udpate max water -> result
maxWater = max(maxWater, water)
#update index left or right depending on height
if height[left] < height[right] :
left += 1
else :
right -= 1
return maxWater
반응형