Minimum Cost Tree From Leaf Values - 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

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.

Input & Output

Example 1 — Basic Case
$ Input: arr = [6,2,4]
Output: 32
💡 Note: There are two possible trees. The first has non-leaf node sum 36, the second has non-leaf node sum 32. Tree 1: ((6,2),4) → cost = 6*2 + max(6,2)*4 = 12 + 24 = 36. Tree 2: (6,(2,4)) → cost = 2*4 + 6*max(2,4) = 8 + 24 = 32.
Example 2 — Minimum Size
$ Input: arr = [4,11]
Output: 44
💡 Note: Only one possible tree with root having value 4*11 = 44.
Example 3 — Multiple Elements
$ Input: arr = [1,2,3,4]
Output: 28
💡 Note: Optimal grouping: (1,(2,(3,4))) → costs: 3*4=12, 2*4=8, 1*4=4, total=28.

Constraints

  • 2 ≤ arr.length ≤ 40
  • 1 ≤ arr[i] ≤ 15
  • It is guaranteed that the answer fits in a 32-bit signed integer (i.e., it is less than 231)

Visualization

Tap to expand
Minimum Cost Tree From Leaf Values INPUT Array arr: 6 idx 0 2 idx 1 4 idx 2 Leaves in in-order: root node 4 6 2 Leaves: 6, 2, 4 (in-order) ALGORITHM STEPS 1 Initialize Stack Push arr[0]=6 to stack stack: [6], cost: 0 2 Process arr[1]=2 2 < 6, push to stack stack: [6,2], cost: 0 3 Process arr[2]=4 4 > 2, pop 2, merge cost += min(6,4)*2 = 8 stack: [6,4], cost: 8 4 Merge Remaining Pop 4, merge with 6 cost += 6*4 = 24 stack: [6], cost: 32 Final Stack State: 6 max leaf FINAL RESULT Optimal Binary Tree: 24 8 4 leaf 6 leaf 2 leaf Non-leaf sum: 8 + 24 = 32 Output: 32 Key Insight: Use a monotonic decreasing stack. When a larger element comes, merge the smaller element with the minimum of its neighbors. This greedy approach minimizes cost by always removing the smallest leaf first. Time: O(n), Space: O(n) TutorialsPoint - Minimum Cost Tree From Leaf Values | Greedy with Stack
Asked in
Google 15 Amazon 12 Microsoft 8
89.0K Views
Medium Frequency
~25 min Avg. Time
2.1K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen