KatInterview

Minimum Days to Complete Sequential Tasks With Daily Time Budgets

Greedy & IntervalsAuto-graded · 27 test cases
EasyAuto-gradedGreedy & Intervalsgreedysimulationtwo-pointers

Last updated

Greedy single-pass simulation: pack tasks in order into daily time budgets without splitting, and return the day count or -1 if impossible.

You are working through a list of tasks that must be done strictly in the given order. Each day offers a fixed amount of working time, and each task needs a fixed amount of time. A task must be completed entirely within one day; it cannot be paused and continued on another day.

Given budget, where budget[i] is the working time available on day i, and tasks, where tasks[j] is the time needed by task j, return the smallest number of days required to complete every task. If the tasks cannot all be completed using the days provided, return -1.

Rules

  • Tasks are done in order: task j + 1 can only be started after task j is complete.
  • Days are used in order beginning with day 0. A day may be left with no work done on it.
  • Unused time on a day is lost and does not roll over to the next day.
  • A day can hold several tasks as long as their total time does not exceed that day's budget (an exact fit is allowed).
  • The answer is the smallest d such that all tasks can be completed using only days 0 through d - 1. If no such d <= len(budget) exists, return -1.
  • If there are no tasks, the answer is 0.
  • Days that were skipped or wasted still count toward the total, because the answer is determined by the last day used.

Constraints

  • 1 <= len(budget) <= 100000
  • 0 <= len(tasks) <= 100000
  • 0 <= budget[i] <= 10000
  • 1 <= tasks[j] <= 10000

Examples

Example 1

Input: min_days_to_complete([3, 5, 2, 6], [2, 2, 3, 4])

Output: 4

Example 2

Input: min_days_to_complete([4, 4], [5])

Output: -1

Example 3

Input: min_days_to_complete([10, 1], [3, 3, 4])

Output: 1

Hints

Hint 1

Process the days from first to last and keep a pointer to the next task that has not yet been done.

Hint 2

On each day, keep taking the next task while its time still fits in what remains of that day. As soon as the next task does not fit, the day is over, because you cannot skip ahead.

Hint 3

Taking tasks as early as possible never hurts, since leftover time is lost anyway. Return the index of the day on which the last task is done plus one, and handle the empty task list before the loop.