인자인 height는 숫자로 이루어진 배열입니다.그래프로 생각한다면 y축의 값이고,
높이 값을 갖고 있습니다.
아래의 그래프라면 height 배열은 [1, 8, 6, 2, 5, 4, 8, 3, 7] 입니다.
저 그래프에 물을 담는다고 생각하고, 물을 담을 수 있는 가장 넓은 면적의 값을 반환해주세요.가정
배열의 길이는 2이상입니다.
height
리스트 첫 번째 요소부터 차례대로 모두 계산하기
데이터가 많다고 생각해보면, 정말 오래걸릴 방법이다.
def get_max_area(height):
max_area = 0
for i in range(len(height)):
for j in range(i+1, len(height)):
area = 0
lower_h = 0
lower_h = height[i] if height[i] < height[j] else height[j]
area = lower_h * (j-i)
max_area = max_area if max_area > area else area
return max_area
양쪽에서 좁히면서 들어오기
def get_max_area(height):
result = 0
left, right = 0, len(height) - 1
height_used = 0
while left < right: # left와 right가 서로 지나치지 않을때까지
if height_used >= height[left]:
left += 1
continue # height_used보다 큰게 없으니 밑에 부분 실행 말고 바로 넘어가기
elif height_used >= height[right]:
right -= 1
continue
height_used = min(height[left], height[right])
result = max(result, (right - left) * height_used)
return result