Given certain jobs with start and end time and amount you make on finishing the job, find the maximum value you can make by scheduling jobs in non-overlapping way.
Dynamic programming solution.
First sort all the jobs in ascending order based on their end time. This makes checking if two jobs overlap or not easier.
State: maxGain[i]: Given the first i jobs, the max profit we can get by selecting jobs[i].
Function: maxGain[i] = max {maxGain[i], maxGain[j] + jobs[i].gain}, for j in [0, i)
Initialization: maxGain[i] = jobs[i].gain, as we know by selecting jobs[i], we at least have a profit of jobs[i].gain.
Answer: the max value of maxGain[i].
1 import java.util.Arrays; 2 3 class Job implements Comparable<Job>{ 4 int start; 5 int end; 6 int gain; 7 Job(int start, int end, int gain) { 8 this.start = start; 9 this.end = end; 10 this.gain = gain; 11 } 12 public int compareTo(Job o) { 13 return this.end - o.end; 14 } 15 } 16 public class WeightedJobScheduling { 17 public int getMaxGain(Job[] jobs) { 18 Arrays.sort(jobs); 19 int[] maxGain = new int[jobs.length]; 20 for(int i = 0; i < maxGain.length; i++) { 21 maxGain[i] = jobs[i].gain; 22 } 23 for(int i = 1; i < maxGain.length; i++) { 24 for(int j = 0; j < i; j++) { 25 if(jobs[i].start >= jobs[j].end) { 26 maxGain[i] = Math.max(maxGain[i], maxGain[j] + jobs[i].gain); 27 } 28 } 29 } 30 31 int max = Integer.MIN_VALUE; 32 for(int i = 0; i < maxGain.length; i++) { 33 if(maxGain[i] > max) { 34 max = maxGain[i]; 35 } 36 } 37 return max; 38 } 39 }