1759. Two-Machine Pipeline

Hard7.5 points estimatedGreedySortingCustom Comparator

A print shop has n booklets to produce. Every booklet must first pass through the printing press for a[i] minutes and then through the binding machine for b[i] minutes. Each machine handles one booklet at a time, and a booklet cannot start binding before its printing has finished. Both machines process the booklets in the same order, and you choose that order. The binding machine may sit idle while it waits for the next booklet to come off the press, and all work starts at time 0.

Given the arrays a and b (both of length n), return the smallest possible time at which the last booklet leaves the binding machine. Totals can reach about 10^12, so return a 64-bit integer. The intended solution sorts the booklets with a two-group rule and then simulates both machines: O(n log n) time and O(n) space.

Example 1

Input:
a = [3,5,1], b = [2,1,4]
Output:
10
Explanation:

Run booklet 2 first (printing ends at 1, binding 1 to 5), then booklet 0 (printing ends at 4, binding 5 to 7), then booklet 1 (printing ends at 9, binding 9 to 10), so the last booklet leaves at time 10.

Example 2

Input:
a = [4], b = [6]
Output:
10
Explanation:

With a single booklet, it prints for 4 minutes and binds for 6 more, finishing at time 10.

Example 3

Input:
a = [2,2], b = [5,3]
Output:
10
Explanation:

Either order finishes at 10: the printing presses are busy until time 4 and the last binding job takes at least 3 more minutes after the binding machine is free at 7.

Constraints

1 ≤ n ≤ 1000, where n = a.length = b.length

1 ≤ a[i], b[i] ≤ 109

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms

Expected complexity

Time
O(n log n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…