Skip to problem
←

Minimum Cost Tree From Leaf Values

Medium 0 attempts

You're given an array arr, and each of its values becomes a leaf of a binary tree, placed left to right so that reading the leaves in order reproduces arr. Every internal node's value equals the product of the largest leaf in its left subtree and the largest leaf in its right subtree. Build the tree so that the total value stored across the internal (non-leaf) nodes is as small as possible, and return that minimum sum.

Every internal node has exactly two children.

Return only the minimum sum; the leaf values themselves do not contribute to it. The internal-node rule uses the largest leaf in each child subtree, not the child root’s value. Leaf order must remain unchanged.

For [6,2,4], combine leaves 2 and 4 under an internal node worth 8. The root is worth 6 × 4 = 24, so the total is 8 + 24 = 32.

Function contract

Implement mctFromLeafValues(arr). The positive integers in arr must be the leaf values in left-to-right order; they cannot be rearranged.

Output: Return the minimum sum of internal-node values. Do not include leaf values or return a tree.

Example 1

Input
arr = [6,2,4]
Output
32

Example 2

Input
arr = [4,11]
Output
44
Visual Aid
Example 1: internal cost 32
Leaves 6, 2, and 4 form a tree with internal costs 24 and 8, totaling 32248624Internal costs only:24 + 8 = 32Return 32Leaf order: 6 → 2 → 4

Circled values are internal-node costs. The root uses leaf maxima 6 and 4, so its value is 24, not 6 × 8.

Constraints
  • 2 <= arr.length <= 40
  • 1 <= arr[i] <= 15

Monotonic Stack (Greedy)

Keep a decreasing stack of unresolved leaf maxima, preceded by an Infinity sentinel. When a new value is at least the stack top, that smaller value can be paired with the smaller of its two available larger neighbors. Pay their product and remove the smaller value: it will no longer be the maximum of any later merged group. Deferring that pairing cannot offer a smaller partner while preserving leaf order.

After the scan, pair the remaining decreasing maxima from right to left. Each value is pushed once and removed once, giving linear time. The sentinel is never included in a cost.

javascript
function mctFromLeafValues(arr) {
  let cost = 0;
  const stack = [Infinity];
  for (const val of arr) {
    while (stack[stack.length-1] <= val) {
      const mid = stack.pop();
      cost += mid * Math.min(stack[stack.length-1], val);
    }
    stack.push(val);
  }
  while (stack.length > 2) cost += stack.pop() * stack[stack.length-1];
  return cost;
}

Time: O(n) | Space: O(n)

Loading discussion…

Saved in this browser only. Private to you.

JavaScript