
[문제]
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 together with the x-axis form a container, such that the container contains the most water.
Return the maximum amount of water a container can store.
Notice that you may not slant the container.
[입력 조건]
n == height.length
2 <= n <= 105
0 <= height[i] <= 104
[내 풀이]
class Solution:
def maxArea(self, height: List[int]) -> int:
max_area = 0
left = 0
right = len(height) - 1
while right > left:
gap = (right - left) * min(height[left], height[right])
max_area = max(max_area, gap)
if height[left] < height[right]:
left += 1
else:
right -= 1
return max_area
모든 배열을 순회하는 건 n2라 조금 더 효율적으로 순회하는 방법을 찾아야했다.
left와 right 변수 두개로 끝에서부터 동시에 비교하는 방법으로 구현했다.
[출처]
https://leetcode.com/problems/container-with-most-water