Minimum Cost Tree From Leaf Values Problem
Description
LeetCode Problem 1130.
Given an array arr of positive integers, consider all binary trees such that:
- Each node has either
0or2children; - The values of
arrcorrespond to the values of each leaf in an in-order traversal of the tree. - The value of each non-leaf node is equal to the product of the largest leaf value in its left and right subtree, respectively.
Among all possible binary trees considered, return the smallest possible sum of the values of each non-leaf node. It is guaranteed this sum fits into a 32-bit integer.
A node is a leaf if and only if it has zero children.
Example 1:

Input: arr = [6,2,4]
Output: 32
Explanation: There are two possible trees shown.
The first has a non-leaf node sum 36, and the second has non-leaf node sum 32.
Example 2:

Input: arr = [4,11]
Output: 44
Constraints:
2 <= arr.length <= 401 <= arr[i] <= 15- It is guaranteed that the answer fits into a 32-bit signed integer (i.e., it is less than 2^31).
Solution
Approach: Interval DP
The leaves appear in order, so the root of any valid tree splits arr at some point k into a left part arr[i..k] and a right part arr[k+1..j], and each part is again a tree of the same kind. The root's value is the product of the largest leaf on each side. That gives a recurrence on intervals.
Let cost[i][j] be the smallest sum of non-leaf values for the leaves arr[i..j], and big[i][j] the largest value in arr[i..j]:
- A single leaf has no non-leaf nodes:
cost[i][i] = 0. - Otherwise try every split:
cost[i][j] = min over i <= k < j of cost[i][k] + cost[k+1][j] + big[i][k] * big[k+1][j].
The answer is cost[0][n-1]. Fill the table so the shorter intervals are ready first, for example i from right to left and j from left to right; big[i][j] can be built in the same loop from big[i][j-1].
The maximum of each part does not depend on how that part is built, which is why the product at the root can be computed from big alone. With n <= 40, the O(n3) work is tiny.
Complexity: O(n3) time and O(n2) extra space.
class Solution:
def mctFromLeafValues(self, arr: List[int]) -> int:
n = len(arr)
# cost[i][j] = smallest sum of non-leaf nodes for leaves arr[i..j]; big[i][j] = max(arr[i..j]).
cost = [[0] * n for _ in range(n)]
big = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
big[i][i] = arr[i]
for j in range(i + 1, n):
big[i][j] = max(big[i][j - 1], arr[j])
# Split into a left subtree arr[i..k] and a right subtree arr[k+1..j]; the root is the product.
cost[i][j] = min(cost[i][k] + cost[k + 1][j] + big[i][k] * big[k + 1][j] for k in range(i, j))
return cost[0][n - 1]