Minimum Time to Consolidate Candies (Krishna)

Added: 2025-09-13 06:47:18

Question Image

Minimum Time to Consolidate Candies (Krishna)

Answer

✏️ Edit
import heapq

# Read number of test cases
T = int(input())

for _ in range(T):
    # Read number of boxes
    N = int(input())
    # Read candy counts
    candies = list(map(int, input().split()))
    
    # Create a min-heap
    heapq.heapify(candies)
    
    total_time = 0
    
    # Combine boxes N-1 times
    while len(candies) > 1:
        # Pop two smallest boxes
        first = heapq.heappop(candies)
        second = heapq.heappop(candies)
        
        # Time to combine them
        combine_time = first + second
        total_time += combine_time
        
        # Push the new combined box back
        heapq.heappush(candies, combine_time)
    
    # Print the total minimum time
    print(total_time)