Skip to content

Commit 8058d69

Browse files
authored
Create minimum-cost-to-connect-sticks.cpp
1 parent 975623c commit 8058d69

File tree

1 file changed

+17
-0
lines changed

1 file changed

+17
-0
lines changed
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Time: O(nlogn)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int connectSticks(vector<int>& sticks) {
7+
priority_queue<int, vector<int>, greater<int>> min_heap(sticks.cbegin(), sticks.cend());
8+
int result = 0;
9+
while (min_heap.size() > 1) {
10+
const auto x = min_heap.top(); min_heap.pop();
11+
const auto y = min_heap.top(); min_heap.pop();
12+
result += x + y;
13+
min_heap.emplace(x + y);
14+
}
15+
return result;
16+
}
17+
};

0 commit comments

Comments
 (0)