Social feed~20 min2s · 256 MBtarget O((n + q) log n) time, O(n) spacecomplexity · prefix-sums
A social app builds each page of the feed by reading posts from the top of a queue. It adds up the size of every post it reads, and it stops as soon as the running size is larger than the page budget. The post that crosses the budget has been read too.
A page with a large budget reads the whole queue, and that is the worst case of the early exit. You will count the posts read over a day of page builds.
Write total_posts_examined(sizes, budgets).
sizes[i] is the size of post i in the queue, from the top.budget in budgets, a page build reads posts 0, 1, 2, ... and adds each size to a running total.budget. If no post does, it reads all of them.A total equal to the budget does not stop the build. It stops only when the total is strictly larger.
Input: sizes = [4, 1, 3, 2, 5], budgets = [0, 4, 5, 9, 100]
Output: 15Each budget reads posts until the running size passes it. The sizes are 4, 1, 3, 2, 5, so the running sizes are 4, 5, 8, 10, 15.
| Budget | Running sizes read | Posts read |
|---|---|---|
| 0 | 4 | 1 |
| 4 | 4, 5 | 2 |
| 5 | 4, 5, 8 | 3 |
| 9 | 4, 5, 8, 10 | 4 |
| 100 | 4, 5, 8, 10, 15 | 5 |
The total is 15.
Input: sizes = [], budgets = [5, 10]
Output: 0With no posts, no page reads anything. The total is 0.
Input: sizes = [7, 7, 7], budgets = [6, 7, 20]
Output: 6Budget 6 stops after the first post, because 7 is more than 6. Budget 7 does not stop at 7, so it reads a second post and stops at 14. Budget 20 reads all three. The total is 1 + 2 + 3 = 6.
0 ≤ sizes.length ≤ 100,000 (posts in the queue)1 ≤ sizes[i] ≤ 10,000 (post sizes)0 ≤ budgets.length ≤ 100,000 (page builds in a day)0 ≤ budgets[j] ≤ 1,000,000,000 (page budgets)Reading the queue for every page costs up to 10^5 × 10^5 = 10^10 reads in the worst case, when the budget is large. The answer can pass 2 × 10^9, so use 64-bit integers. Every page rereads the same prefix sums, so build them once and search.