Given a list of jobs where each job has a start and finish time, and a profit associated with it, find a maximum profit subset of non-overlapping jobs.

For example, consider the following jobs with their starting time, finishing time, and associated profit. The maximum profit is 80, and the jobs involved in the maximum profit are: (1, 4, 30) and (5, 9, 50).

Job 1: (0, 6, 60)
Job 2: (5, 9, 50)
Job 3: (1, 4, 30)
Job 4: (5, 7, 30)
Job 5: (3, 5, 10)
Job 6: (7, 8, 10)

Practice this problem

This post will discuss a dynamic programming solution for Weighted Interval Scheduling Problem, which is nothing but a variation of the Longest Increasing Subsequence (LIS) algorithm.

 
The idea is first to sort given jobs in increasing order of their start time. Let jobs[0…n-1] be the sorted array of jobs. We can define an array maxProfit[] such that maxProfit[i] itself is an array that stores the non-conflicting jobs with maximum profit that ends with the i'th job.

Therefore, maxProfit[i] can be recursively written as:

maxProfit[i] = jobs[i] + { max(maxProfit[j]), where j < i and
                             jobs[j].finish <= jobs[i].start }
             = jobs[i], if there is no such j

To demonstrate, consider the following jobs, which are sorted by their start time:

(0, 6, 60)
(1, 4, 30)
(3, 5, 10)
(5, 7, 30)
(5, 9, 50)
(7, 8, 10)

The maxProfit[] would be:

maxProfit[0]: (0, 6, 60)
maxProfit[1]: (1, 4, 30)
maxProfit[2]: (3, 5, 10)
maxProfit[3]: (1, 4, 30) (5, 7, 30)
maxProfit[4]: (1, 4, 30) (5, 9, 50)
maxProfit[5]: (0, 6, 60) (7, 8, 10)

Now the algorithm picks the one with the highest profit. In the above example, maxProfit[4] has the maximum profit. This can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

The maximum profit is 80

Java


Download  Run Code

Output:

The maximum profit is 80

Python


Download  Run Code

Output:

The maximum profit is 80

The time complexity of the above solution is O(n2) and requires O(n) extra space, where n is the total number of jobs.

How to print the jobs involved in maximum profit?

The idea is similar to the above bottom-up approach using dynamic programming, but we maintain an extra array to store the index of jobs involved in the maximum profit. This is demonstrated below in C++, Java, and Python:

C++


Download  Run Code

Output:

The jobs involved in the maximum profit are (1, 4, 30) (5, 9, 50)

Java


Download  Run Code

Output:

The jobs involved in the maximum profit are (1, 4, 30) (5, 9, 50)

Python


Download  Run Code

Output:

The jobs involved in the maximum profit are (1, 4, 30) (5, 9, 50)

The time complexity of the above solution is O(n2) and requires O(n2) extra space, where n is the total number of jobs.