Ad platform~20 min2s · 256 MBtarget O(n log M) time, O(1) spacebinary-search-answer
You work on the ordering system of a print shop for advertising banners. The shop has rolls of vinyl of different lengths, in whole units. Every banner in an order must have the same length.
After each banner is cut, a hem of 1 unit is lost, except at the very end of a roll. Your team lead asks: "How long can each banner be if we need banners of them?" There can be 100,000 rolls.
Write longest_banner(rolls, banners).
rolls[i] is the length of roll i.L is cut from a roll. A hem of 1 unit is lost after each banner. A banner that ends at the end of the roll needs no hem.r gives (r + 1) // (L + 1) banners of length L.L ≥ 1 for which all rolls together give at least banners banners. Return 0 when even L = 1 is not enough.Input: rolls = [10, 7, 6], banners = 5
Output: 3Try a length and count the banners. Longer banners never give more banners, so we look for the largest length that still gives 5.
| Length | Banners from each roll | Total | At least 5? |
|---|---|---|---|
| 2 | [3, 2, 2] | 7 | yes |
| 3 | [2, 2, 1] | 5 | yes |
| 4 | [2, 1, 1] | 4 | no |
Length 3 gives enough banners and length 4 does not, so the answer is 3.
Input: rolls = [1, 1], banners = 3
Output: 0Two rolls of length 1 give one banner each at length 1, which is 2 in total. Three are needed, so the answer is 0.
Input: rolls = [9], banners = 1
Output: 9One roll of length 9 gives one banner of length 9, because the last banner needs no hem.
1 ≤ len(rolls) ≤ 100,0001 ≤ rolls[i] ≤ 1,000,000,0001 ≤ banners ≤ 1,000,000,000Trying every length from the longest roll down means up to a billion lengths, and each one counts 100,000 rolls. That is far too slow for a 2-second limit. But a longer banner never gives more banners, so "enough banners at length L" is yes for small L and no for large L. A binary search needs about 30 checks.