Imagine you are a freelancer with multiple job offers, each with a start time, end time, and profit. You want to schedule jobs to maximize your total earnings without overlapping any jobs.
Given n jobs where every job is represented as (startTime, endTime, profit), find the maximum profit you can earn by scheduling non-overlapping jobs. You may choose to skip some jobs. Return the maximum profit achievable.
1 ≤ n ≤ 10^51 ≤ startTime[i], endTime[i], profit[i] ≤ 10^9startTime[i] < endTime[i]
Edge cases: All jobs overlap completely → output is max single job profitJobs with same start and end times but different profits → pick highest profit jobJobs sorted in descending order of end time → algorithm must still work
def jobScheduling(startTime: List[int], endTime: List[int], profit: List[int]) -> int:public int jobScheduling(int[] startTime, int[] endTime, int[] profit)int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit)function jobScheduling(startTime, endTime, profit)
def jobScheduling(startTime, endTime, profit):
# Write your solution here
pass
class Solution {
public int jobScheduling(int[] startTime, int[] endTime, int[] profit) {
// Write your solution here
return 0;
}
}
#include <vector>
using namespace std;
int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
// Write your solution here
return 0;
}
function jobScheduling(startTime, endTime, profit) {
// Write your solution here
}
Common Bugs to Avoid
Wrong: Less than max profit due to greedy scheduling by earliest end timeUsing greedy approach instead of DP with binary search for last non-conflicting job✅ Implement DP recurrence dp[i] = max(dp[i-1], profit[i] + dp[last_non_conflict]) with binary search to find last non-conflicting job
Wrong: Sum of all profits ignoring overlapsNot enforcing non-overlapping constraint in DP or binary search✅ Ensure binary search finds last job that ends before current job starts and add dp[last_non_conflict] only if no overlap
Wrong: Incorrect result due to unsorted jobsNot sorting jobs by end time before DP and binary search✅ Sort jobs by end time before processing and binary searching
Wrong: Crash or wrong output on empty inputNo base case handling for empty input arrays✅ Add base case: if no jobs, return 0 immediately
Wrong: Wrong profit for single job inputDP initialization incorrect for single element✅ Initialize dp[0] = profit[0] for single job input