Social feed~30 min2s · 256 MBtarget O(n + q) time, O(n) spaceclassic twin: lc-45greedy
A news app shows a stack of story cards, numbered from 0. A reader starts on card 0. The skip button on card i jumps forward by 1 to reach[i] cards. A card with a reach of 0 has no skip button.
Product analysts ask many questions of one stack. For a number of skips, which is the farthest card a reader can reach by using at most that many skips? The reader never goes past the last card.
Write farthest_after_skips(reach, budgets).
reach[i] is the largest jump from card i. A jump moves forward by any number of cards from 1 to reach[i], but never beyond the last card.budgets[j], find the largest card number that a reader starting at card 0 can reach with at most that many skips.Input: reach = [2,3,1,0,4,1,0,0], budgets = [0,1,2,3,10]
Output: [0,2,4,7,7]The solution builds the farthest card for each number of skips, layer by layer. A layer is made from all cards that the previous layer reaches.
| Skips | Cards reachable | Best jump from them | Farthest card |
|---|---|---|---|
| 0 | 0 | none yet | 0 |
| 1 | 0 to 2 | card 0 jumps 2 | 2 |
| 2 | 0 to 4 | card 1 jumps 3, to card 4 | 4 |
| 3 | 0 to 7 | card 4 jumps 4, to card 8, capped at 7 | 7 |
The answers for the budgets 0, 1, 2, 3 and 10 are 0, 2, 4, 7 and 7.
Input: reach = [2,3,1,0,4,1,0,0], budgets = [5]
Output: [7]The reader reaches the last card, card 7, after 3 skips. More skips cannot take the reader further, so 5 skips give 7.
Input: reach = [0,5,5], budgets = [1,2]
Output: [0,0]Card 0 has a reach of 0, so the reader cannot leave it. The answer is 0 for every budget.
1 ≤ len(reach) ≤ 100,000, and 0 ≤ reach[i] ≤ 100,0001 ≤ len(budgets) ≤ 100,000, and 0 ≤ budgets[j] ≤ 1,000,000,000Trying every skip for every question costs about 100,000 questions times up to 100,000 skips times 100,000 cards, which is far beyond any computer. One pass over the cards builds all the layers, at most 100,000 of them. Each question is then a single look-up, so the work is about 200,000 steps.