Minimum Cost to Connect Sticks

medium heap greedy

Problem

You have sticks with positive integer lengths. You can connect any two sticks into one for a cost equal to the sum of their lengths. Return the minimum total cost of connecting all sticks into a single stick.

Inputsticks = [2, 4, 3]
Output14
Combine 2+3=5 (cost 5), then 5+4=9 (cost 9). Total = 5+9 = 14.

import heapq

def connect_sticks(sticks):
    heapq.heapify(sticks)
    cost = 0
    while len(sticks) > 1:
        a = heapq.heappop(sticks)
        b = heapq.heappop(sticks)
        cost += a + b
        heapq.heappush(sticks, a + b)
    return cost
function connectSticks(sticks) {
  const h = new MinHeap(sticks);
  let cost = 0;
  while (h.size() > 1) {
    const a = h.pop();
    const b = h.pop();
    cost += a + b;
    h.push(a + b);
  }
  return cost;
}
class Solution {
    public int connectSticks(int[] sticks) {
        PriorityQueue<Integer> pq = new PriorityQueue<>();
        for (int s : sticks) pq.offer(s);
        int cost = 0;
        while (pq.size() > 1) {
            int a = pq.poll();
            int b = pq.poll();
            cost += a + b;
            pq.offer(a + b);
        }
        return cost;
    }
}
int connectSticks(vector<int>& sticks) {
    priority_queue<int, vector<int>, greater<int>> pq(sticks.begin(), sticks.end());
    int cost = 0;
    while ((int)pq.size() > 1) {
        int a = pq.top(); pq.pop();
        int b = pq.top(); pq.pop();
        cost += a + b;
        pq.push(a + b);
    }
    return cost;
}
Time: O(n log n) Space: O(n)