#1130

Minimum Cost Tree From Leaf Values

Medium
ArrayDynamic ProgrammingStackGreedyMonotonic StackDynamic ProgrammingDivide and Conquer
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n³)
Space
O(1)
O(n²)
💡

Intuition

Time O(n³)Space O(n²)

The optimal solution uses dynamic programming to store intermediate results, avoiding redundant calculations. By leveraging the properties of the binary tree structure, we can efficiently compute the minimum cost without generating all possible trees.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP table where dp[i][j] represents the minimum cost for the subarray arr[i] to arr[j].
  2. 2Step 2: Iterate through all possible lengths of subarrays and fill the DP table based on previously computed values.
  3. 3Step 3: For each subarray, find the maximum leaf values and compute the cost using the DP table.
solution.py12 lines
1def minCost(arr):
2    n = len(arr)
3    dp = [[0] * n for _ in range(n)]
4    for length in range(2, n + 1):
5        for i in range(n - length + 1):
6            j = i + length - 1
7            max_left = max(arr[i:j + 1])
8            for k in range(i, j):
9                max_right = max(arr[k + 1:j + 1])
10                cost = max_left * max_right + dp[i][k] + dp[k + 1][j]
11                dp[i][j] = min(dp[i][j], cost) if dp[i][j] else cost
12    return dp[0][n - 1]

Complexity note: The time complexity is O(n³) due to the nested loops for subarray lengths, starting index, and partition index. The space complexity is O(n²) because we maintain a DP table to store results for subarrays.

  • 1Dynamic programming can significantly reduce redundant calculations.
  • 2Understanding tree structures helps in optimizing the problem-solving approach.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.