Skip to the content

The sacks before the rain

Problem

Remedios watches the clouds from the threshing floor and already knows what is coming: the rain arrives in hours hours and any grain left out is lost. On the floor there are piles of ears of wheat, each one with its sacks, and the thresher parks at one pile when the hour begins. It stays there the whole hour, even if it finishes the pile halfway through, and it never splits an hour between two piles.

The mechanic sets the thresher to whatever capacity she asks for: the sacks it grinds in one hour, always from the same pile. A pile takes as many hours as it takes to cut its sacks into pieces of that capacity, and the last piece takes a whole hour too, even if it goes half empty: a pile of 7 sacks with capacity 3 takes 3 hours.

A bigger machine never takes longer: if the whole floor is threshed before the rain with one capacity, it is threshed with any higher one too. The higher the capacity, the more the grain gets battered, so Remedios wants the smallest one that saves her harvest.

Write a function that takes piles, a list of positive whole numbers with the sacks in each pile (at least one, in any order), and hours, a whole number that is never less than the number of piles. Return a whole number: the smallest capacity that gets the whole floor threshed in hours hours or less.

With piles of 3, 6, 7 and 11 sacks and 8 hours, the answer is 4: the piles take 1, 2, 2 and 3 hours, which is exactly 8. With capacity 3 they would take 1, 2, 3 and 4, which is 10, and the rain catches them lying out in the open.

Careful with the rough estimate: sharing the total sacks out among the hours does not give the answer, because the biggest pile takes its hours on its own and the hours of the small ones are no help to it. And there are floors with up to 50 piles of a billion sacks, so trying one capacity at a time does not finish either.

Examples

  • The example

    [3, 6, 7, 11], 8 → 4

  • Sharing the total out among the hours is not enough

    [30, 11, 23, 4, 20], 6 → 23

  • One hour per pile

    [3, 6, 7, 11], 4 → 11

  • A pile of a billion in one hour

    [1000000000], 1 → 1000000000

  • There are hours to spare

    [3, 6, 7, 11], 27 → 1

Besides these, the challenge has hidden tests that are revealed when you submit your solution.

You start with this

Python

def per_hour(piles, hours):
    pass

JavaScript

function perHour(piles, hours) {
}
Solve this challenge

It opens in your browser, with the editor and the tests. This challenge is part of the full plan; the O(1) and O(log n) ones are free.

More O(n log n) challenges

See all challenges →