Greedy The best choice now
503. Shortest Job First
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]
4Explanation: 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]
0Explanation: The only job starts at time 0, so it waits 0.
Example 3
Input: burstTimes = [1000000000, 1000000000, 1000000000, 1000000000]
1500000000Explanation: 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.
Constraints
1 ≤ burstTimes.length ≤ 1051 ≤ burstTimes[i] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.