Skip to content

Commit c4b8ffc

Browse files
authored
Create 1130-minimum-cost-tree-from-leaf-values.js
1 parent 12307f8 commit c4b8ffc

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed
+20
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* @param {number[]} arr
3+
* @return {number}
4+
*/
5+
const mctFromLeafValues = function(arr) {
6+
let res = 0, n = arr.length;
7+
let stack = new Array();
8+
stack.push(Number.MAX_VALUE);
9+
for (let a of arr) {
10+
while (stack[stack.length - 1] <= a) {
11+
let mid = stack.pop();
12+
res += mid * Math.min(stack[stack.length - 1], a);
13+
}
14+
stack.push(a);
15+
}
16+
while (stack.length > 2) {
17+
res += stack.pop() * stack[stack.length - 1];
18+
}
19+
return res;
20+
};

0 commit comments

Comments
 (0)