1167. Minimum Cost to Connect Sticks
Input: sticks = [2,4,3]
Output: 14Input: sticks = [1,8,3,5]
Output: 30// Priority_Queue (Min heap)
int connectSticks(vector<int>& sticks) { // time: O(log(n!)); space: O(n)
priority_queue<int, vector<int>, greater<int> > pq(sticks.begin(), sticks.end());
int res = 0;
while (pq.size() > 1) {
int a = pq.top(); pq.pop();
int b = pq.top(); pq.pop();
pq.push(a + b);
res += (a + b);
}
return res;
}Last updated