Skip to the content

The height of the saw

Problem

Filomena, who is a forest ranger, was asked for meters meters of wood from the woodland she looks after, and she set one condition: not a single tree comes down. The crew brings a saw that is fixed at one height, goes over the whole woodland and takes away everything that sticks out above that height. A tree of 20 meters with the saw at 15 leaves 5 meters of wood. One of 10 meters leaves nothing, because the saw passes over it without touching it.

The higher the saw is fixed, the less wood comes out, and Filomena cares about leaving the woodland as whole as she can. She wants the highest height that still gathers the meters of the order.

Write a function that takes trees, a list of positive whole numbers with the height of each tree (at least one, in any order), and meters, a positive whole number that never goes above the sum of all the heights. Return a whole number: the highest height, in whole meters, at which the cut wood reaches or passes the meters of the order.

With trees of 20, 15, 10 and 17 meters and an order of 7, the answer is 15: 5 come out of the first one and 2 out of the last one, which is exactly the 7. With the saw at 16 it would be 4 and 1, that is 5, and the order falls short.

Height 0 always works, because with the saw on the ground the whole woodland comes out: with two trees of 5 meters and an order of 10, the answer is 0.

Sharing the order out among the trees is no use: the cut is the same for all of them and the short trees put in nothing. The heights reach a billion and there are woodlands with up to 60 trees, so raising the saw one meter at a time does not finish either.

Examples

  • The example

    [20, 15, 10, 17], 7 → 15

  • The saw on the ground

    [5, 5], 10 → 0

  • Five trees of two digits

    [4, 42, 40, 26, 46], 20 → 36

  • A single tree

    [100], 30 → 70

  • One meter of wood

    [20, 15, 10, 17], 1 → 19

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

You start with this

Python

def cut_height(trees, meters):
    pass

JavaScript

function cutHeight(trees, meters) {
}
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 →