Engineering platform~22 min2s · 256 MBtarget O(n log S) time, O(1) spacebinary-search-answer
You work on the backup service of a hosting platform. Files wait in a queue, and a nightly run copies a stretch of consecutive files, in queue order. A run may copy at most max_files files and at most a chosen total size, the cap.
Your team lead asks: "We can run at most nights nights. What is the smallest cap that still copies the whole queue?" The queue can hold 100,000 files.
Write smallest_nightly_cap(sizes, nights, max_files).
sizes[i] is the size of file i, in queue order.max_files files, with a total size of at most the cap.nights nights are allowed.-1 when no cap works, because even a cap equal to the total size needs more than nights nights.Input: sizes = [4, 2, 6, 3, 5, 1], nights = 3, max_files = 3
Output: 9Try a cap and fill each night greedily: add the next file while the cap and the file limit allow. A larger cap never needs more nights, so we look for the smallest cap that fits in 3 nights.
| Cap | Nights needed | Fits in 3 nights? |
|---|---|---|
| 8 | 4 | no |
| 9 | 3 | yes |
| 10 | 3 | yes |
A cap of 8 needs more than 3 nights, and a cap of 9 fits, so the answer is 9.
Input: sizes = [5, 5, 5, 5], nights = 2, max_files = 1
Output: -1One file per night means four nights for four files, and only two nights are allowed. No cap helps, so the answer is -1.
Input: sizes = [7], nights = 1, max_files = 1
Output: 7One file of size 7 needs a cap of 7.
1 ≤ len(sizes) ≤ 100,0001 ≤ sizes[i] ≤ 1,000,0001 ≤ nights ≤ 100,0001 ≤ max_files ≤ 100,000Trying every cap from the largest file up to the total size means up to 10^11 caps. Trying every way to cut the queue into nights is even larger. But a bigger cap never needs more nights, so the caps that work form a block at the large end. A binary search over the cap needs about 37 checks, each a single pass over the queue.