An office printer serves n queued print jobs, numbered 0 to n-1, arranged in a fixed circular order. Job i still needs pages[i] more pages printed. The printer visits the jobs in order 0, 1, 2, ..., n-1, 0, 1, ..., repeating forever: when it reaches a job that still needs at least one more page, it prints exactly one page for that job (this takes exactly one second) and moves on to the next job in the cycle; when it reaches a job that has already finished (zero pages remaining), it moves on immediately without spending any time.
Given the page counts and a target job index, determine the exact second at which the target job prints its very last remaining page.
The first line contains two integers n and target, separated by a space, where target is a valid 0-indexed job number.
The second line contains n space-separated integers pages[0], pages[1], ..., pages[n-1].
A single integer: the second at which job target completes its final page.
Example 1
Input
3 2 2 3 2
Expected
6
Explanation
Job pages are [2,3,2], target=2. Pass 1 prints one page each for jobs 0,1,2 (seconds 1,2,3), leaving [1,2,1]. Pass 2 prints one page each again (seconds 4,5,6), leaving [0,1,0]. Job 2 hits zero on second 6, so the answer is 6.
Example 2
Input
4 0 5 1 1 1
Expected
8
Explanation
Job pages are [5,1,1,1], target=0. Job 0 needs 5 pages total, so it is printed on seconds 1,5,6,7,8 as the cycle revisits it (jobs 1,2,3 finish after one page each and are skipped on later passes). Job 0's fifth and final page prints on second 8, so the answer is 8.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →