Social feed~25 min2s · 256 MBtarget O(n log m) time, O(1) spaceclassic twin: lc-875binary-search-answer
A social app has a moderation tool with several queues of reported posts. A moderator reviews at a steady rate of rate posts per hour and works on one queue at a time.
If a queue has fewer than rate posts left, the moderator finishes it and waits for the next hour to start another queue. The team has hours hours to clear every queue. What is the slowest whole rate that still clears them all in time?
Write slowest_rate(queues, hours).
queues[i] is the number of posts in queue i.r posts per hour, queue i takes ceil(queues[i] / r) hours, because the moderator never switches queues in the middle of an hour.r (at least 1) such that all the queues together take at most hours hours.Input: queues = [3, 6, 7, 11], hours = 8
Output: 4The rate can be anything from 1 to 11, because 11 posts an hour clears each queue in one hour. A rate r is fast enough when the hours add up to at most 8. Search the window [lo, hi), where hi is always fast enough.
| Step | lo | hi | mid | hours needed at mid | Decision |
|---|---|---|---|---|---|
| 1 | 1 | 11 | 6 | 1 + 1 + 2 + 2 = 6 | 6 <= 8, fast enough, so hi = 6 |
| 2 | 1 | 6 | 3 | 1 + 2 + 3 + 4 = 10 | 10 > 8, too slow, so lo = 4 |
| 3 | 4 | 6 | 5 | 1 + 2 + 2 + 3 = 8 | 8 <= 8, so hi = 5 |
| 4 | 4 | 5 | 4 | 1 + 2 + 2 + 3 = 8 | 8 <= 8, so hi = 4 |
| end | 4 | 4 | the slowest rate that finishes is 4 |
The rate 3 needs 10 hours, which is too many, so 4 is the answer.
Input: queues = [10], hours = 1
Output: 10One queue and one hour: the rate must clear all 10 posts in that hour, so the answer is the top of the range, 10.
Input: queues = [5, 5, 5], hours = 100
Output: 1With plenty of time, even 1 post an hour takes 15 hours, so the answer is the bottom of the range, 1.
1 ≤ queues.length ≤ 100,0001 ≤ queues[i] ≤ 1,000,000,000 postsqueues.length ≤ hours ≤ 1,000,000,000, so each queue can get at least one hourTrying every rate from 1 upwards, and adding up the hours for each, costs about n × (the answer) steps. The answer can be about 10^8, so that is far beyond 10^10. Checking one rate costs n steps, and a binary search over the rates from 1 to 10^9 needs only about 30 checks, so about 3 × 10^6 steps.