(Medium #11) Container With Most Water
because of timelimit 문제가 생각보다 발생 / 앞으로 슬슬 신경써야 할 듯..
Problem
Given n non-negative integers a1, a2, ..., an , where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
Note: You may not slant the container and n is at least 2.

The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the max area of water (blue section) the container can contain is 49.
Example:
Input: [1,8,6,2,5,4,8,3,7] Output: 49
My solution
class Solution:
def maxArea(self, height: List[int]) -> int:
maxarea = 0
height_set = list(set(height))
height_set.sort()
start = 0
end = len(height)-1
for i in range(len(height_set)):
for k in range(start,len(height)):
if height[k]>=height_set[i]:
start = k
break
for k in range(end,-1,-1):
if height[k]>=height_set[i]:
end = k
break
x = end-start
y = height_set[i]
maxarea = max(maxarea, x*y)
return maxarea
Runtime: 168ms, Memory: 16MBdef maxArea(self, height: List[int]) -> int:
maxarea = 0
height_set = list(set(height))
height_set.sort()
start = 0
end = len(height)-1
for i in range(len(height_set)):
for k in range(start,len(height)):
if height[k]>=height_set[i]:
start = k
break
for k in range(end,-1,-1):
if height[k]>=height_set[i]:
end = k
break
x = end-start
y = height_set[i]
maxarea = max(maxarea, x*y)
return maxarea
Other people solution
class Solution:
def maxArea(self, height: List[int]) -> int:
max_area = 0
i = 0
j = len(height)-1
while i < j :
max_area = max(min(height[i],height[j])*(j-i), max_area)
if height[i] <= height[j]:
i += 1
else:
j -= 1
return max_area
Runtime: 144ms, Memory: 15.4MBdef maxArea(self, height: List[int]) -> int:
max_area = 0
i = 0
j = len(height)-1
while i < j :
max_area = max(min(height[i],height[j])*(j-i), max_area)
if height[i] <= height[j]:
i += 1
else:
j -= 1
return max_area
댓글
댓글 쓰기