class Solution def solve self st end if st end in self return self st

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution:
d = {}
def solve(self, st, end):
if (st, end) in self.d:
return self.d[(st, end)]
max_v, sum_v = None, None
for i in range(st, end):
max_l, sum_l = self.solve(st, i)
max_r, sum_r = self.solve(i+1, end)
#print(self.d)
max_c, sum_c = max(max_l, max_r), sum_l + sum_r + max_l*max_r
if sum_v is None or sum_c < sum_v:
max_v = max_c
sum_v = sum_c
self.d[(st, end)] = (max_v, sum_v)
return max_v, sum_v
def mctFromLeafValues(self, arr: List[int]) -> int:
self.d = {}
for i in range(len(arr)):
self.d[(i, i)] = (arr[i], 0)
max_v, ans = self.solve(0, len(arr)-1)
return ans