candle count problem

Added: 2025-09-13 00:51:27

Question Image

candle count problem

Answer

✏️ Edit
import heapq

def min_time_to_collect_all_candies(boxes):
    # Use a min-heap to always combine the smallest two boxes
    heapq.heapify(boxes)
    total_time = 0

    while len(boxes) > 1:
        first = heapq.heappop(boxes)
        second = heapq.heappop(boxes)
        time_taken = first + second
        total_time += time_taken
        heapq.heappush(boxes, time_taken)

    return total_time

# Read input
t = int(input())
for _ in range(t):
    n = int(input())
    boxes = list(map(int, input().split()))
    result = min_time_to_collect_all_candies(boxes)
    print(result)