Minimum Cost Tree From Leaf Values — LeetCode 1130 Python Solution

MediumStackGreedyArrayDynamic ProgrammingMonotonic Stack
Problem
#1130
Pattern
Stack
Reading time
3 min

The problem

Given an array arr of positive integers, consider all binary trees such that: Each node has either 0 or 2 children; The values of arr correspond 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.

Example

Input
arr = [6,2,4]
Output
32
Explanation
There are two possible trees shown.

Python solution

Python
class Solution:
    def mctFromLeafValues(self, arr: List[int]) -> int:
        @cache
        def dfs(i: int, j: int) -> Tuple:
            if i == j:
                return 0, arr[i]
            s, mx = inf, -1
            for k in range(i, j):
                s1, mx1 = dfs(i, k)
                s2, mx2 = dfs(k + 1, j)
                t = s1 + s2 + mx1 * mx2
                if s > t:
                    s = t
                    mx = max(mx1, mx2)
            return s, mx

        return dfs(0, len(arr) - 1)[0]

Complexity

MeasureComplexity
TimeO(n^3)
SpaceO(n^2) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 1130. Minimum Cost Tree From Leaf Values is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1130. Minimum Cost Tree From Leaf Values?
LeetCode 1130. Minimum Cost Tree From Leaf Values is rated Medium on LeetCode.
What is the time complexity of LeetCode 1130. Minimum Cost Tree From Leaf Values?
The Python solution on this page runs in O(n^3).
What is the space complexity of LeetCode 1130. Minimum Cost Tree From Leaf Values?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 1130. Minimum Cost Tree From Leaf Values cover?
LeetCode 1130. Minimum Cost Tree From Leaf Values is tagged Stack, Greedy, Array, Dynamic Programming and Monotonic Stack on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview