Minimum Time to Complete All Deliveries Problem
Description
LeetCode Problem 3733.
You are given two integer arrays of size 2: d = [d_1, d_2] and r = [r_1, r_2].
Two delivery drones are tasked with completing a specific number of deliveries. Drone i must complete d_i deliveries.
Each delivery takes exactly one hour and only one drone can make a delivery at any given hour.
Additionally, both drones require recharging at specific intervals during which they cannot make deliveries. Drone i must recharge every r_i hours (i.e. at hours that are multiples of r_i).
Return an integer denoting the minimum total time (in hours) required to complete all deliveries.
Example 1:
Input: d = [3,1], r = [2,3]
Output: 5
Explanation:
- The first drone delivers at hours 1, 3, 5 (recharges at hours 2, 4).
- The second drone delivers at hour 2 (recharges at hour 3).
Example 2:
Input: d = [1,3], r = [2,2]
Output: 7
Explanation:
- The first drone delivers at hour 3 (recharges at hours 2, 4, 6).
- The second drone delivers at hours 1, 5, 7 (recharges at hours 2, 4, 6).
Example 3:
Input: d = [2,1], r = [3,4]
Output: 3
Explanation:
- The first drone delivers at hours 1, 2 (recharges at hour 3).
- The second drone delivers at hour 3.
Constraints:
d = [d_1, d_2]1 <= d_i <= 10^9r = [r_1, r_2]2 <= r_i <= 3 * 10^4
Solution
Approach: Binary Search on the Time
If all deliveries can be finished within T hours, they can also be finished within T + 1 hours, so we can binary search on T.
Within the first T hours, drone i is free in T - floor(T / r_i) hours. Each hour only one drone delivers, and an hour can be used only if at least one drone is free. Both drones are busy exactly in the hours that are multiples of lcm(r_1, r_2), so the usable hours number T - floor(T / lcm). The deliveries fit within T hours exactly when
d_1 <= T - floor(T / r_1),d_2 <= T - floor(T / r_2),d_1 + d_2 <= T - floor(T / lcm).
Binary search for the smallest T satisfying all three. At least half of all hours are usable (since r_i >= 2), so T <= 4 * 10^9 + 10 always suffices; using 10^10 as the upper bound is safe.
Complexity: time O(log(d_1 + d_2)), space O(1).
from math import gcd
class Solution:
def minimumTime(self, d: List[int], r: List[int]) -> int:
l = r[0] * r[1] // gcd(r[0], r[1])
lo, hi = 1, 10**10
while lo < hi:
t = (lo + hi) // 2
if (d[0] <= t - t // r[0] and d[1] <= t - t // r[1]
and d[0] + d[1] <= t - t // l):
hi = t
else:
lo = t + 1
return lo