Minimum Cost Tree From Leaf Values - Problem

Imagine you're a tree architect tasked with building the most cost-effective binary tree from a given arrangement of leaf values! ๐ŸŒณ

Given an array arr of positive integers, you need to construct a binary tree where:

  • Each node has either 0 or 2 children (no single-child nodes)
  • The leaf values correspond to an in-order traversal of your array
  • Each non-leaf node's value equals the product of the maximum leaf value in its left subtree and the maximum leaf value in its right subtree

Your mission: minimize the sum of all non-leaf node values across all possible tree configurations!

Example: For [6, 2, 4], you could build different trees, but the optimal one gives you the smallest sum of internal node costs.

Input & Output

example_1.py โ€” Basic Case
$ Input: [6, 2, 4]
โ€บ Output: 32
๐Ÿ’ก Note: We can build different trees, but the optimal one has structure where 2 and 4 are merged first (cost = 2ร—4=8), then combined with 6 (cost = 6ร—4=24). Total cost = 8 + 24 = 32.
example_2.py โ€” Already Optimal
$ Input: [4, 11]
โ€บ Output: 44
๐Ÿ’ก Note: With only two leaves, we must merge them directly. The cost is simply 4 ร— 11 = 44.
example_3.py โ€” Decreasing Sequence
$ Input: [15, 13, 5, 3, 1]
โ€บ Output: 500
๐Ÿ’ก Note: In a decreasing sequence, we merge from right to left: (3ร—1=3) + (5ร—3=15) + (13ร—5=65) + (15ร—13=195) = 278. Actually, optimal is different - we need to be more careful about the tree structure.

Constraints

  • 2 โ‰ค arr.length โ‰ค 40
  • 1 โ‰ค arr[i] โ‰ค 15
  • It is guaranteed this sum fits into a 32-bit integer
  • Each node has either 0 or 2 children (binary tree property)

Visualization

Tap to expand
Tournament Bracket AnalogyOriginal Array: [6, 2, 4]624Step 1: Merge 2 and 4 first (smaller values)2ร—4=8246Step 2: Merge with 6 (cost = 6ร—4 = 24)6ร—4=246max=4๐ŸŽฏ Total Cost: 8 + 24 = 32Strategy: Merge smaller values first to minimize future costs!
Understanding the Visualization
1
Identify Pattern
Smaller teams should meet larger teams as late as possible
2
Use Stack
Maintain decreasing order - when disrupted, resolve conflicts
3
Calculate Costs
Each merge costs the product of the maximum values from each side
4
Greedy Choice
Always make locally optimal decisions for globally optimal result
Key Takeaway
๐ŸŽฏ Key Insight: Use a monotonic stack to greedily process elements, always merging smaller values first to minimize the total cost. This transforms an exponential problem into a linear one!
Asked in
Google 15 Amazon 12 Meta 8 Microsoft 6
45.7K Views
Medium Frequency
~15 min Avg. Time
1.8K 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