KatInterview

Count Total Pipeline Output Within Time Constraint

Greedy & IntervalsAuto-graded · 22 test cases
MediumAuto-gradedGreedy & Intervalsgreedyarraysmath

Last updated

Compute the maximum number of items processed by a sequential single-threaded worker within a total allowed time limit.

You are managing an automated linear processing pipeline consisting of $n$ distinct, ordered phases (indexed $0$ through $n-1$). A single worker handles jobs sequentially through these phases. The worker must completely finish all required items in phase $i$ before starting any work on phase $i + 1$.

You are provided two integer arrays of length $n$:

  • item_counts[i]: the number of units to process in phase $i$.
  • unit_times[i]: the execution time needed for a single unit in phase $i$.

You are also given an integer max_time representing the maximum time units available to the worker. A unit of work is considered complete if and only if its full duration finishes at or before max_time. If the time limit is reached while a unit is still being processed, that unit is not counted as completed, and the worker halts instantly.

Return the total count of fully finished units across all phases within max_time.

Constraints

  • $n == \text{len}(item_counts) == \text{len}(unit_times)$
  • $1 \le n \le 10^5$
  • $0 \le item_counts[i] \le 10^9$
  • $0 \le unit_times[i] \le 10^9$
  • $0 \le max_time \le 10^{18}$

Examples

Example 1

Input: count_completed_units([3, 2, 5], [4, 10, 2], 25)

Output: 4

Example 2

Input: count_completed_units([0, 4, 2], [5, 0, 3], 4)

Output: 5

Hints

Hint 1

Simulating each job one by one will be too slow because item counts can be up to 10^9 per phase.

Hint 2

Instead of individual units, use integer division to determine how many units of the current phase can finish in the remaining time.

Hint 3

Be careful with zero unit times (to avoid division by zero) and zero item counts, and remember to halt as soon as a non-empty phase cannot be fully finished.