oneby7

Greedy The best choice now

503. Shortest Job First

Medium

A CPU has n jobs to run, and burstTimes[i] is how long job i takes. All the jobs are ready at time 0. The CPU runs one job at a time, and once a job starts, it runs to the end without a pause. The jobs may run in any order.

A job's waiting time is the time from 0 until the job starts. It is the sum of the burst times of the jobs that run before it. The job's own burst time does not count.

Return the smallest possible average waiting time of the n jobs, rounded down to an integer.

Example 1

Input: burstTimes = [6, 2, 9, 3]

Output: 4

Explanation: Run the jobs in the order 2, 3, 6, 9. They wait 0, 2, 5 and 11, so the average is 18 / 4 = 4.5, which rounds down to 4. The given order would make them wait 0, 6, 8 and 17, an average of 7.75.

Example 2

Input: burstTimes = [5]

Output: 0

Explanation: The only job starts at time 0, so it waits 0.

Example 3

Input: burstTimes = [1000000000, 1000000000, 1000000000, 1000000000]

Output: 1500000000

Explanation: The jobs are equally long, so every order gives the same waits: 0, 109, 2 × 109 and 3 × 109. They add up to 6 × 109, and the average is 1500000000.

Check your understanding

Work out the answer for this input before you write any code.

burstTimes = [7, 2, 4]

Constraints

  • 1 ≤ burstTimes.length ≤ 105
  • 1 ≤ burstTimes[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.