Ctrl K

Tree of Leaf Products

Medium
You are given an array of positive integers leaves. Consider every binary tree such that: - each node has either 0 or 2 children; - reading the leaves from left to right gives exactly leaves; - each inner node holds the largest leaf of its left subtree times the largest leaf of its right subtree. Among all such trees, return the smallest possible sum of the inner node values.
Example 1
leaves=[3, 5, 2] → 25

Merge 5 and 2 first (node 10), then 3 with that subtree (3 × 5 = 15): sum 25. Starting with 3 and 5 (15) and then adding 2 (5 × 2 = 10) also gives 25. Nothing smaller is possible.

Example 2
leaves=[6, 9] → 54

There is only one tree: a single inner node 6 × 9 = 54.

Example 3
leaves=[1, 8, 1, 8] → 80
Constraints
  • 2 ≤ len(leaves) ≤ 40
  • 1 ≤ leaves[i] ≤ 15
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsHopping Along the Stones MediumRaising by Ranges HardEqualizer Sliders to a Preset HardFix the Middle of the Line MediumMost Pieces Sorted Separately Medium
loading Python…
Input
leaves=[3, 5, 2]
Expected
25

Run checks the first 3 tests in your browser. Submit checks all 95 tests on the server, hidden ones included.