← All Exercises

Weighted Shortest Processing Time Scheduling

intermediatejavascript~20min

Background

WSPT is the classic exchange-argument result from scheduling theory: swapping any adjacent inversion strictly improves the objective, so the sorted order is optimal for a single machine.

Problem

Schedule jobs to minimize the sum over jobs of weight times completion time. The optimal greedy orders jobs by decreasing weight divided by processing time, breaking ties by job id. Output the job order, each job completion time, and the weighted sum.

Input

A JSON object {"jobs": [{"id": string, "w": number, "p": number}]} with positive weights and processing times.

Output

A JSON object {"order": string[], "completionTimes": object, "weightedSum": number}.

Sample tests

Sample 1

Input: {"jobs":[{"id":"a","w":3,"p":2},{"id":"b","w":1,"p":1},{"id":"c","w":2,"p":1}]}
Expected: {"order":["c","a","b"],"completionTimes":{"c":1,"a":3,"b":4},"weightedSum":15}

Sample 2

Input: {"jobs":[{"id":"x","w":2,"p":2},{"id":"y","w":1,"p":1}]}
Expected: {"order":["x","y"],"completionTimes":{"x":2,"y":3},"weightedSum":7}

Your solution

Learning objective

Implement the exchange-argument greedy and compute its objective value.