Skip to the content

Who waits the least

Problem

All the orders reach Mateo at once, and his kitchen has a single stove: he cooks one order at a time, one after another, with no breaks. He picks the order, and he knows a long dish at the start keeps everyone behind it waiting.

Write a function that takes times, a list of positive integers (the minutes each order takes; it may be empty), and returns an integer: the total wait of all the customers, with the orders in whatever sequence makes it smallest. Each customer waits from the moment the orders come in until their own order starts cooking, so the first one waits 0.

With [3, 1, 2], the best is to go 1, 2 and 3: they wait 0, 1 and 1 + 2 = 3, and the total is 4. With no orders, or just one, the answer is 0.

Examples

  • The one from the example

    [3, 1, 2] → 4

  • A single order

    [5] → 0

  • No orders

    [] → 0

  • Equal orders

    [4, 4, 4] → 12

  • Four orders in a jumble

    [8, 2, 5, 1] → 12

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

You start with this

Python

def total_wait(times):
    pass

JavaScript

function totalWait(times) {
}
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 →