인자인 height는 숫자로 이루어진 배열입니다.그래프로 생각한다면 y축의 값이고, 높이 값을 갖고 있습니다.
아래의 그래프라면 height 배열은 [1, 8, 6, 2, 5, 4, 8, 3, 7] 입니다.
저 그래프에 물을 담는다고 생각하고, 물을 담을 수 있는 가장 넓은 면적의 값을 반환해주세요.
요구사항 : 배열의 숫자들과 index를 갖고 가장 넓은 면적의 값을 구해라.
제한사항 : 리스트의 길이는 2이상
인풋 : 숫자의 리스트
아웃풋 : 숫자
본질 : 각각의 숫자를 height로, 각각의 index 사이의 간격을 width로 구해라.
def get_max_area(height):
print(height)
result = 0
for i1, h1 in enumerate(height):
for i2, h2 in enumerate(height):
min_h = min(h1, h2)
width = i2 - i1
area = min_h * width
if area > result:
result = area
return result
by 예랑님.
첫번째 방법과 접근은 같지만, 반복문의 횟수가 줄어들었다.
range에서 i+1 인덱스부터 시작함으로써, 이미 비교한 값들끼리는 반복문을 실행하지 않는다.
def get_max_area(height):
result = 0
for i in range(0, len(height)):
h1 = height[i]
for j in range(i+1, len(height)):
h2 = height[j]
area = min(h1, h2) * abs(i-j)
if area > result:
result = area
return result
abs함수를 쓰는 대신, j에서 i를 빼도 된다. 어차피 i의 다음 인덱스이니까.
by 준영님 동명님.
각각의 height(바)에서 뽕을 뽑은 다음 index를 옮겨간다고 생각하면 편하다.
def get_max_area(height):
result = 0
left, right = 0, len(height) - 1
main_height = 0
while left < right :
if main_height >= height[left]:
left += 1
if main_height >= height[right]:
right -= 1
main_height = min(height[left], height[right])
area_as = abs(left-right) * main_height
if area_as > result:
result = area_as
return result