KatInterview

Minimum Days to Execute Sequential Jobs with Cooldown

Greedy & IntervalsAuto-graded · 21 test cases
MediumAuto-gradedGreedy & Intervalsgreedyhash-mapsimulation

Last updated

Simulates executing a fixed sequence of jobs where re-running the same job requires waiting through a cooldown period.

You have a list of jobs that must be executed in the exact order given. Each job is identified by an integer ID and takes one day to complete. Only one job can run per day.

After completing a job with ID x on day d, you cannot run another job with the same ID x until at least cooldown days have passed. Specifically, the next time you can execute job x is on day d + cooldown + 1 or later.

If a job cannot be scheduled on the current day due to its cooldown restriction, that day becomes idle and no work is performed.

Return the minimum number of days required to complete all jobs in the given sequence.

Constraints

  • 1 <= len(jobs) <= 2 * 10^5
  • 0 <= jobs[i] <= 10^9
  • 0 <= cooldown <= 10^5

Examples

Example 1

Input: min_days_to_complete_tasks([1, 2, 1, 3, 2, 1], 2)

Output: 7

Example 2

Input: min_days_to_complete_tasks([1, 1, 1], 3)

Output: 9

Example 3

Input: min_days_to_complete_tasks([1, 2, 3, 4], 100)

Output: 4

Hints

Hint 1

Track the most recent execution day for each job ID using a dictionary.

Hint 2

For each job, determine the earliest day it can run based on both the cooldown constraint and the requirement to run after the previous job.

Hint 3

The answer is simply the day on which the final job completes—idle days are implicitly counted in the gaps.