The algorithm

Arrays.sort(jobs, (a, b) -> b.profit - a.profit);  // desc by profit
int maxDeadline = maxDeadlineFromJobs();
boolean[] slots = new boolean[maxDeadline];
int totalProfit = 0;
for (Job j : jobs) {
  for (int t = min(j.deadline, maxDeadline) - 1; t >= 0; t--) {
    if (!slots[t]) { slots[t] = true; totalProfit += j.profit; break; }
  }
}
Advertisement

Why greedy works

Sort by profit descending. Latest possible slot for each job. If any slot before deadline is free, take it.

Advertisement

Complexity

O(N²) naive. O(N log N) with Union-Find to find 'next free slot before deadline' in O(α(N)).

Related

CPU scheduling. Interview scheduling. Any deadline-based single-resource allocation.