#1130
Medium Algorithms Minimum cost tree from leaf values
Array Dynamic Programming Stack Greedy Monotonic Stack
67.8% acceptance
Feb 25, 2026
4430
282
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, respectively.
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.
Solution
Rust
Time O(n²)
Space O(n)
impl Solution {
pub fn mct_from_leaf_values(arr: Vec<i32>) -> i32 {
let mut stack: Vec<i32> = vec![i32::MAX];
let mut result = 0;
for &v in &arr {
while *stack.last().unwrap() <= v {
let mid = stack.pop().unwrap();
result += mid * (*stack.last().unwrap()).min(v);
}
stack.push(v);
}
while stack.len() > 2 {
let mid = stack.pop().unwrap();
result += mid * *stack.last().unwrap();
}
result
}
}