Untitled

 avatar
unknown
plain_text
12 days ago
1.1 kB
2
Indexable
class Solution {
    public int connectSticks(int[] sticks) {
        // Initialize a minimum heap (priority queue) to store the sticks in ascending order
        PriorityQueue<Integer> minHeap = new PriorityQueue<>();
      
        // Add all the sticks to the heap
        for (int stick : sticks) {
            minHeap.offer(stick);
        }
      
        // Initialize the total cost to connect all the sticks
        int totalCost = 0;
      
        // Continue combining sticks until only one stick remains
        while (minHeap.size() > 1) {
            // Retrieve and remove the two smallest sticks
            int stick1 = minHeap.poll();
            int stick2 = minHeap.poll();
          
            // Calculate the cost of connecting the two smallest sticks
            int cost = stick1 + stick2;
          
            // Add the cost to the total cost
            totalCost += cost;
          
            // Add the combined stick back to the heap
            minHeap.offer(cost);
        }
      
        // Return the total cost to connect all the sticks
        return totalCost;
    }
}
Leave a Comment