LeetCode 1130. Minimum Cost Tree From Leaf Values

Problem Statement


impl Solution {
pub fn mct_from_leaf_values(arr: Vec<i32>) -> i32 {
let (mut ans, n) = (0, arr.len());
let mut stack = vec![];
stack.push(std::i32::MAX);
for a in &arr {
while stack.last().unwrap() <= a {
let mid = stack.last().unwrap().clone();
stack.pop();
ans += mid * std::cmp::min(stack.last().unwrap(), a);
}
stack.push(*a);
}

let mut i = 2;
while i < stack.len() {
ans += stack[i] * stack[i - 1];
i += 1;
}
return ans;
}
}