Repair crew order
MediumOnline Assessment
Choose the order in which a repair crew should visit damaged sites so the total loss is smallest.
After a storm, one crew must repair n sites, one after another, starting at hour 0. Site i takes hours hours to repair and, until its repair is finished, costs loss per hour in lost business. Every hour counts from hour 0, so a site whose repair finishes at hour F costs F * loss in total. The crew never idles and never leaves a site half-repaired.
Among all orders that give the smallest total loss, choose the lexicographically smallest one: compare the site numbers in visiting order, and the order with the smaller number at the first difference wins.
Input: jobs, a list of [hours, loss] pairs; site i is jobs[i].
Output: the list of site numbers in the order they are visited, for the order with the smallest total loss (and, among those, the lexicographically smallest). If there are no sites, return an empty list.
With up to 1,000 sites the number of possible orders is astronomical, so trying them is not an option. Comparing two sites by dividing their numbers can be misleading when the numbers are large: compare exactly.
Example 1
- Input:
- [[[3,9],[1,2],[2,4]]]
- Output:
- [0,1,2]
- Explanation
- The ratios hours/loss are 1/3, 1/2 and 1/2, so site 0 goes first and sites 1 and 2 are tied. Visiting 0, 1, 2 finishes at hours 3, 4 and 6, costing 3*9 + 4*2 + 6*4 = 59. Visiting 1, 2, 0 (shortest job first) would cost 2*2 + 3*4 + 6*9 = 70, and 59 is the best there is. Sites 1 and 2 cost the same in either order, so the smaller site number goes first.
Example 2
- Input:
- [[[5,0],[2,1],[4,0],[1,3]]]
- Output:
- [3,1,0,2]
- Explanation
- Sites 0 and 2 cost nothing while they wait, so they go last, in site order. Sites 3 and 1 have ratios 1/3 and 2, so 3 goes first. They finish at hours 1 and 3 (costing 1*3 and 3*1), and the free sites add nothing, for a total of 6: [3, 1, 0, 2].
Example 3
- Input:
- [[[4,2],[6,3],[2,1],[3,5]]]
- Output:
- [3,0,1,2]
- Explanation
- Sites 0, 1 and 2 all have ratio 2 and site 3 has ratio 3/5, so site 3 goes first and then the three tied sites in site order. They finish at hours 3, 7, 13 and 15, costing 15 + 14 + 39 + 15 = 83: [3, 0, 1, 2].
Constraints
0 <= jobs.length <= 1,000- each job is
[hours, loss]with1 <= hours <= 1,000,000,000and0 <= loss <= 1,000,000,000