Search~10 min2s · 256 MBtarget O(n) time, O(1) spacetraversal
The search box of an online store shows its results page by page. Every page holds the same number of results, except the last page of a search, which may be partly filled. A search with no results needs no page.
Your team lead wants to size the page cache. For a list of searches, each with its number of results, you report how many pages the store would build in total. The counts are large, so the first attempt that builds the pages one by one is slow.
Write pages_needed(result_counts, page_size).
result_counts[i] is the number of results of search i.page_size results. The last page of a search may hold fewer.Input: result_counts = [25, 40, 0, 7], page_size = 10
Output: 8Each row is one search.
| Search | Results | Full pages | Partly filled page | Pages |
|---|---|---|---|---|
| 0 | 25 | 2 | yes, 5 results | 3 |
| 1 | 40 | 4 | no | 4 |
| 2 | 0 | 0 | no | 0 |
| 3 | 7 | 0 | yes, 7 results | 1 |
The total is 3 + 4 + 0 + 1 = 8 pages.
Input: result_counts = [10, 20, 30], page_size = 10
Output: 6Every count is an exact multiple of the page size, so no page is partly filled: 1 + 2 + 3 = 6 pages.
Input: result_counts = [1], page_size = 100
Output: 1One result still needs one page.
1 ≤ result_counts.length ≤ 1,000 (searches in the list)0 ≤ result_counts[i] ≤ 1,000,000,000 (results of one search)1 ≤ page_size ≤ 1,000 (results on a full page)Building the pages one at a time means up to 10^9 steps for one search, and the list has up to 1,000 searches. That is about 10^12 steps, far beyond the 10^8 a second you can plan with. The total of pages can also pass 2 × 10^9, so it needs a 64-bit integer.