Editorial for Battery Pack Merging


Approach

Sort the battery packs from largest to smallest, then keep taking packs in that order until the running total is at least TT.

If the sum of all packs is still below TT, the answer is -1.

Time complexity is O(nlog⁡n)O(n \log n).

Solution (Python)

Code 1
import sys


data = [int(x) for x in sys.stdin.buffer.read().split()]
n = data[0]
target = data[1]
capacities = data[2 : 2 + n]

capacities.sort(reverse=True)

charge = 0
for used, capacity in enumerate(capacities, start=1):
    charge += capacity
    if charge >= target:
        print(used)
        break
else:
    print(-1)

Comments0


No comments yet

Be the first to comment.

New comment


Log in to join the discussion.