Skip to content

Commit fefea77

Browse files
authored
Create minimum-cost-tree-from-leaf-values.cpp
1 parent 800d541 commit fefea77

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int mctFromLeafValues(vector<int>& arr) {
7+
int result = 0;
8+
vector<int> stk = {numeric_limits<int>::max()};
9+
for (const auto& x : arr) {
10+
while (stk.back() <= x) {
11+
const auto mid = move(stk.back()); stk.pop_back();
12+
result += mid * min(stk.back(), x);
13+
}
14+
stk.emplace_back(x);
15+
}
16+
while (stk.size() > 2) {
17+
const auto right = move(stk.back()); stk.pop_back();
18+
result += right * stk.back();
19+
}
20+
return result;
21+
}
22+
};

0 commit comments

Comments
 (0)