Job i runs from startTime[i] to endTime[i] and earns profit[i]. Choose non-overlapping jobs to maximize total profit. A job may start exactly when another ends.
Same recurrence, but since jobs are sorted by end time, binary search for the last job ending at or before the current start.
1function jobScheduling(startTime: number[], endTime: number[], profit: number[]): number {2const jobs = startTime.map((s, i) => [s, endTime[i], profit[i]]).sort((a, b) => a[1] - b[1]);3const dp = new Array(jobs.length + 1).fill(0);4for (let i = 1; i <= jobs.length; i++) {5const [s, , p] = jobs[i - 1];6let lo = 0, hi = i - 1; // count of jobs ending by s7while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (jobs[mid - 1][1] <= s) lo = mid; else hi = mid - 1; }8dp[i] = Math.max(dp[i - 1], dp[lo] + p);9}10return dp[jobs.length];11}
Sort jobs by end time.
Space: play/pause · ←/→: step