Overview
Given n jobs where job i has startTime[i], endTime[i], and profit[i], find the maximum profit by selecting non-overlapping jobs. You can start a new job at the moment another ends.
Constraints
1 <= n <= 50,0001 <= startTime[i] < endTime[i] <= 10^91 <= profit[i] <= 10,000
Examples
jobScheduling([1,2,3,3], [3,4,5,6], [50,10,40,70]); // => 120 (jobs [1,3]+[3,6] → 50+70) jobScheduling([1,1,1], [2,3,4], [5,6,4]); // => 6
Solution
Reveal solution
function jobScheduling(startTime, endTime, profit) {
const n = startTime.length;
const jobs = startTime.map((s, i) => [s, endTime[i], profit[i]]);
jobs.sort((a, b) => a[1] - b[1]);
const dp = [0];
const ends = [0];
for (const [s, e, p] of jobs) {
let lo = 0, hi = ends.length - 1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (ends[mid] <= s) lo = mid; else hi = mid - 1;
}
const take = dp[lo] + p;
const skip = dp[dp.length - 1];
dp.push(Math.max(take, skip));
ends.push(e);
}
return dp[dp.length - 1];
}Sort by end time, then DP: for each job binary search the latest non-overlapping job.
Resources
maximum-profit-job-scheduling.js
Maximum Profit in Job Scheduling
hardcodingAlgorithmsDynamic Programming
Overview
Given n jobs where job i has startTime[i], endTime[i], and profit[i], find the maximum profit by selecting non-overlapping jobs. You can start a new job at the moment another ends.
Constraints
1 <= n <= 50,0001 <= startTime[i] < endTime[i] <= 10^91 <= profit[i] <= 10,000
Examples
jobScheduling([1,2,3,3], [3,4,5,6], [50,10,40,70]); // => 120 (jobs [1,3]+[3,6] → 50+70) jobScheduling([1,1,1], [2,3,4], [5,6,4]); // => 6
Solution
Reveal solution
function jobScheduling(startTime, endTime, profit) {
const n = startTime.length;
const jobs = startTime.map((s, i) => [s, endTime[i], profit[i]]);
jobs.sort((a, b) => a[1] - b[1]);
const dp = [0];
const ends = [0];
for (const [s, e, p] of jobs) {
let lo = 0, hi = ends.length - 1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (ends[mid] <= s) lo = mid; else hi = mid - 1;
}
const take = dp[lo] + p;
const skip = dp[dp.length - 1];
dp.push(Math.max(take, skip));
ends.push(e);
}
return dp[dp.length - 1];
}Sort by end time, then DP: for each job binary search the latest non-overlapping job.
Resources
NameTopicDifficulty
103 of 103 problems