Taro Logo

Maximum Profit in Job Scheduling

#3 Most AskedHard
150 views
Topics:
ArraysBinary SearchDynamic Programming

We have n jobs, where every job is scheduled to be done from startTime[i] to endTime[i], obtaining a profit of profit[i].

You're given the startTime, endTime and profit arrays, return the maximum profit you can take such that there are no two jobs in the subset with overlapping time range.

If you choose a job that ends at time X you will be able to start another job that starts at time X.

Example 1:

Input: startTime = [1,2,3,3], endTime = [3,4,5,6], profit = [50,10,40,70]
Output: 120
Explanation: The subset chosen is the first and fourth job. 
Time range [1-3]+[3-6] , we get profit of 120 = 50 + 70.

Example 2:

Input: startTime = [1,2,3,4,6], endTime = [3,5,10,6,9], profit = [20,20,100,70,60]
Output: 150
Explanation: The subset chosen is the first, fourth and fifth job. 
Profit obtained 150 = 20 + 70 + 60.

Example 3:

Input: startTime = [1,1,1], endTime = [2,3,4], profit = [5,6,4]
Output: 6

Constraints:

  • 1 <= startTime.length == endTime.length == profit.length <= 5 * 104
  • 1 <= startTime[i] < endTime[i] <= 109
  • 1 <= profit[i] <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the ranges and data types for the start times, end times, and profits? Can profits or times be negative or zero?
  2. Are the start and end times inclusive or exclusive? For example, if Job A ends at time 5 and Job B starts at time 5, are they considered overlapping?
  3. Is the input array of jobs guaranteed to be sorted by start time or end time, or should my solution handle an unsorted list?
  4. What should the function return if the input job list is empty, or if no valid non-overlapping jobs can be scheduled?
  5. Can multiple jobs have identical start and end times with different profits, and how should we handle such duplicates?

Brute Force Solution

Approach

Imagine you are offered a massive pile of freelance jobs, and you want to figure out the absolute best combination of jobs to accept so you make the most money without ever doubling up on your schedule. The brute force approach involves looking at every single possible combination of jobs that do not overlap in time, adding up the total payment for each combination, and picking the one that pays the most.

Here's how the algorithm would work step-by-step:

  1. Start by looking at the very first job in your pile and imagine what happens if you accept it versus if you reject it.
  2. If you accept that job, immediately cross off every other job on your list that happens at the same time because you cannot be in two places at once.
  3. For all the remaining jobs that do not overlap, repeat the exact same process of deciding whether to accept or reject them.
  4. Keep branching out like this until you have mapped out every single combination of non-overlapping jobs that you could possibly work.
  5. Whenever you reach the end of a combination, add up the total earnings from all the jobs you chose in that specific scenario.
  6. Compare the total earnings of every single scenario you mapped out.
  7. Finally, select the single scenario that yielded the highest total payout and that is your winning strategy.

Code Implementation

def job_scheduling_brute_force(start_times, end_times, profits): 
    job_collection = [] 
    
    for job_index in range(len(start_times)): 
        job_collection.append((start_times[job_index], end_times[job_index], profits[job_index])) 
        
    def explore_job_combinations(current_index, previous_end_time): 
        # We stop searching when we have evaluated every available job in the collection
        if current_index >= len(job_collection): 
            return 0 
            
        current_start, current_end, current_profit = job_collection[current_index] 
        
        profit_if_rejected = explore_job_combinations(current_index + 1, previous_end_time) 
        
        profit_if_accepted = 0 
        # We can only accept the current job if it does not overlap with the previous one
        if current_start >= previous_end_time: 
            profit_if_accepted = current_profit + explore_job_combinations(current_index + 1, current_end) 
            
        return max(profit_if_rejected, profit_if_accepted) 
        
    job_collection.sort(key=lambda job_tuple: job_tuple[0]) 
    
    # We begin the recursive exploration from the first job with no previous end time
    return explore_job_combinations(0, 0)

Big(O) Analysis

Time Complexity
O(2ⁿ) – For each of the n jobs in our pile, the algorithm branches into two separate decisions: either accepting the job or rejecting it. This branching behavior creates a binary decision tree of depth n as we evaluate every possible combination of non-overlapping jobs. Exploring every single combination requires visiting up to 2ⁿ leaf nodes in the worst-case scenario. This exponential growth means the total operations approximate 2 raised to the nth power, which simplifies to O(2ⁿ).
Space Complexity
O(n) – To implement the strategy of sorting jobs by their end times and storing intermediate maximum profits, we utilize an auxiliary array or dynamic programming table of size N, where N is the total number of jobs. Additionally, the sorting process requires extra memory on the call stack or temporary storage proportional to N. When mapping out the non-overlapping scenarios through recursion or iterative tracking, the storage scales directly with the number of jobs. Therefore, the total auxiliary space complexity simplifies to Big O of N.

Optimal Solution

Approach

Instead of checking every single combination of jobs, the optimal strategy sorts the jobs by their finish times so we can process them in order. As we consider each job, we cleverly combine its payout with the best possible prior payout from jobs that finished before it could start.

Here's how the algorithm would work step-by-step:

  1. Gather all the available jobs and sort them by the time they finish, so the ones that end earliest come first.
  2. Imagine keeping a running diary of the best total earnings you could achieve up to each point in time.
  3. Go through the sorted jobs one by one, deciding for each job whether it is better to skip it and keep your current earnings, or take it and add its pay to the best possible earnings from earlier jobs that did not overlap.
  4. As you finish evaluating each job, update your running diary to reflect the highest possible earnings you could have accumulated by that job's finish time.
  5. Continue this process until you have considered every available job, ensuring you never double-book overlapping times.
  6. Finally, the last entry in your diary will represent the absolute maximum profit you can make from the entire set of jobs without needing to test every possible schedule.

Code Implementation

import bisect


def job_scheduling(start_times, end_times, profits):
    combined_jobs = sorted(zip(start_times, end_times, profits), key=lambda job: job[1])
    
    timeline_finish = [0]
    timeline_profit = [0]
    
    # Sorting by finish times ensures we always consider earlier ending jobs first.
    for current_start, current_end, current_profit in combined_jobs:
        
        previous_index = bisect.bisect_right(timeline_finish, current_start) - 1
        accumulated_profit = timeline_profit[previous_index] + current_profit
        
        # We take the maximum profit by choosing to either skip or take the current job.
        if accumulated_profit > timeline_profit[-1]:
            timeline_finish.append(current_end)
            timeline_profit.append(accumulated_profit)
            
    # The last entry holds the maximum accumulated profit across all evaluated jobs.
    return timeline_profit[-1]

Big(O) Analysis

Time Complexity
O(n log n) – Sorting the n jobs by their finish times takes O(n log n) time. Then, iterating through the n sorted jobs and using binary search to find the latest non-overlapping job takes O(log n) time per job, contributing O(n log n) for the full loop. Combining these steps results in approximately n log n plus n log n operations, which simplifies to O(n log n).
Space Complexity
O(n) – To implement the strategy of processing jobs in order, we store the sorted jobs and maintain a running diary of accumulated earnings as an auxiliary list of size n, where n is the total number of jobs. Additionally, searching for the best non-overlapping prior job requires auxiliary space for internal data structures during sorting and lookups. Therefore, the total extra memory consumed scales linearly with the input size n, resulting in an auxiliary space complexity of O(n).

Edge Cases

Empty input arrays for start, end, or profit
How to Handle:
Return zero profit immediately since no jobs exist to schedule.
Single job input where arrays contain only one element
How to Handle:
Return that single job profit directly without needing any interval comparisons.
All jobs overlap with each other in time
How to Handle:
The algorithm correctly evaluates each individually and returns the maximum single profit among them.
All jobs are completely disjoint and non-overlapping
How to Handle:
Dynamic programming with binary search will successfully accumulate and return the sum of all job profits.
Jobs with identical start and end times
How to Handle:
Sorting by end time ensures zero-duration jobs are processed correctly alongside overlapping intervals.
Maximum possible scale with tens of thousands of jobs
How to Handle:
Using sorting combined with binary search ensures an efficient O(N log N) time complexity that easily passes within time limits.
Extremely large profit values causing integer overflow
How to Handle:
Using 64-bit integer types for the profit accumulation prevents arithmetic overflow during summation.
Jobs that start at the exact moment another job ends
How to Handle:
Treating the condition as non-overlapping allows adjacent back-to-back jobs to be scheduled together.
0/57 completed