~/problems / Greedy

Fewest gondolas for pairs of children

easy ~15 min

Write min_gondolas(weights: list[int], limit: int) -> int.

Children with the given weights want to ride a Ferris wheel. A gondola holds one or two children, and their total weight must not exceed limit. Every child weighs at most limit. Return the minimum number of gondolas needed so that every child rides.

Example: weights = [7, 2, 3, 9], limit = 10 gives 3. 9 must ride alone, then e.g. 7 + 3 and 2. weights = [5, 5, 5, 5], limit = 10 gives 2.

Constraints: 1 <= len(weights) <= 2 * 10^5, 1 <= weights[i] <= limit <= 10^9.

Searching for a partner per child is O(n²) and fails the large test; aim for O(n log n).

Show hint

think about the heaviest child first: they need a gondola no matter what, and the best companion to try for them is the one least likely to be useful to anyone else.

Topic: Greedy with sorting. Sort, then take the locally best choice; prove it with an exchange argument.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc