4048. Minimum Time to Complete All Deliveries
My accepted Python solution to LeetCode problem 4048, Minimum Time to Complete All Deliveries, running in 22ms.
- Difficulty: Medium
- Python
- Runtime 22ms
- Memory 17.3MB
- Updated
Read the problem on LeetCode View on GitHub
The problem statement is LeetCode’s and stays on their site. What follows is my accepted solution.
Python
Accepted on LeetCode — runtime 22ms, memory 17.3MB, accepted 2025-12-30.
class Solution:
def minimumTime(self, d: List[int], r: List[int]) -> int:
d1, d2 = d
r1, r2 = r
def can_complete(T):
# Hours drone i can work in [1, T] = T - (number of multiples of r[i] in [1,T])
# Multiples of r in [1, T] = T // r
work1 = T - T // r1
work2 = T - T // r2
# Each drone must have enough work hours for its deliveries
if work1 < d1 or work2 < d2:
return False
# Total work capacity must be enough, but we also need to check
# if there are enough non-overlapping hours
# Since we have 2 drones and they can't work at same hour,
# we need: hours where at least one can work >= d1 + d2
# Hours where drone 1 can work: not multiples of r1
# Hours where drone 2 can work: not multiples of r2
# They overlap when hour is not multiple of r1 AND not multiple of r2
# Hours where both can work (overlap) = T - (multiples of r1 or r2)
# By inclusion-exclusion: |A ∪ B| = |A| + |B| - |A ∩ B|
# Multiples of r1 or r2 in [1,T] = T//r1 + T//r2 - T//lcm(r1,r2)
from math import gcd
lcm = r1 * r2 // gcd(r1, r2)
# Hours that are multiples of r1 or r2 (hours where neither can work fully)
# Actually: hours where drone 1 is recharging = multiples of r1
# Hours where drone 2 is recharging = multiples of r2
# Let's think differently:
# both_work = hours where both can work = T - (mult of r1) - (mult of r2) + (mult of lcm)
# only_1 = hours where only drone 1 can work = mult of r2 but not r1
# only_2 = hours where only drone 2 can work = mult of r1 but not r2
# neither = mult of both = mult of lcm
mult1 = T // r1 # drone 1 recharges
mult2 = T // r2 # drone 2 recharges
mult_lcm = T // lcm # both recharge
only1_can = mult2 - mult_lcm # hours where only drone 1 can work (drone 2 recharging, drone 1 not)
only2_can = mult1 - mult_lcm # hours where only drone 2 can work
both_can = T - mult1 - mult2 + mult_lcm # hours where both can work
# Drone 1 needs d1 hours, can use only1_can + some of both_can
# Drone 2 needs d2 hours, can use only2_can + some of both_can
# First use dedicated hours
need1 = max(0, d1 - only1_can)
need2 = max(0, d2 - only2_can)
# Check if shared hours are enough for remaining needs
return need1 + need2 <= both_can
# Binary search
left, right = 1, 2 * (d1 + d2) * max(r1, r2)
while left < right:
mid = (left + right) // 2
if can_complete(mid):
right = mid
else:
left = mid + 1
return left