Skip to content

Commit e04a005

Browse files
authored
Create minimum-cost-tree-from-leaf-values.py
1 parent fefea77 commit e04a005

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
class Solution(object):
5+
def mctFromLeafValues(self, arr):
6+
"""
7+
:type arr: List[int]
8+
:rtype: int
9+
"""
10+
result = 0
11+
stk = [float("inf")]
12+
for x in arr:
13+
while stk[-1] <= x:
14+
result += stk.pop() * min(stk[-1], x)
15+
stk.append(x)
16+
while len(stk) > 2:
17+
result += stk.pop() * stk[-1]
18+
return result

0 commit comments

Comments
 (0)