oneby7

Greedy The best choice now

504. Job Sequencing

Medium

You are given n jobs, numbered from 0 to n − 1. Job i has a deadline deadlines[i] and a profit profits[i].

Time starts at 0. Every job takes exactly one unit of time, and you can work on only one job at a time, so the jobs you choose run one after another in the units from 0 to 1, from 1 to 2, and so on. A unit may also stay empty. Job i earns profits[i] if it finishes by time deadlines[i]. You do not have to do every job, and a job you skip earns nothing.

Choose the jobs and their order so that the total profit is as large as possible. Return a list of two numbers: how many jobs that schedule does, and its total profit.

Example 1

Input: deadlines = [2, 4, 1, 2, 4, 3] profits = [30, 60, 10, 45, 20, 25]

Output: [4,160]

Explanation: Run job 0 from time 0 to 1, job 3 from 1 to 2, job 5 from 2 to 3 and job 1 from 3 to 4. Each one finishes by its deadline, and together they earn 30 + 45 + 25 + 60 = 160. No deadline is past 4, so no schedule can fit a fifth job.

Example 2

Input: deadlines = [1000000000, 2, 1000000000] profits = [1000000000, 1000000000, 1000000000]

Output: [3,3000000000]

Explanation: There is time for all three jobs, for example job 1 first and then the other two.

Example 3

Input: deadlines = [1, 1, 1, 1], profits = [5, 9, 3, 9]

Output: [1,9]

Explanation: Every job must finish by time 1, so only one job fits. Either job with profit 9 will do.

Check your understanding

Work out the answer for this input before you write any code.

deadlines = [2, 1, 1, 2], profits = [60, 10, 40, 20]

Constraints

  • 1 ≤ n ≤ 105, where n is deadlines.length
  • profits.length == n
  • 1 ≤ deadlines[i] ≤ 109
  • 1 ≤ profits[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.