Skip to main content

Tree Algorithm

Question

Solution

Tree Algorithm
def solution(arr):
left_id = 0
right_id = len(arr) - 1

max_area = 0

while left_id < right_id:
if arr[left_id] >= arr[right_id]:
right_id = right_id - 1
else:
left_id = left_id + 1

area = min(arr[left_id], arr[right_id]) * (right_id - left_id)

max_area = max(max_area, area)

return max_area


arr = [2, 1, 8, 6, 2, 5, 4, 8, 3, 7, 1, 2]
print(solution(arr))
Tree Algorithm
from gen.util.print_out_manager import print_out


def solution(arr):
left_id = 0
right_id = len(arr) - 1

max_area = 0

while left_id < right_id:
area = min(arr[left_id], arr[right_id]) * (right_id - left_id)
max_area = max(max_area, area)

print_out(left_id, right_id, arr[left_id], arr[right_id], area)

if arr[left_id] >= arr[right_id]:
right_id = right_id - 1
else:
left_id = left_id + 1

return max_area


arr = [2, 1, 8, 6, 2, 5, 4, 8, 3, 7, 1, 2]
result = solution(arr)

print_out(result)

Stepleft_idright_idarr[left_id]arr[right_id]area
10112222
20102110
3092718
419178
5298749
6288318
7278840
8268416
9258515
1024824
1123866
result
49