Best k-day run in a cyclic sprint schedule
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked at Amazon. It tests prefix sums, sliding window and math.
A training program is made of n back-to-back sprints. Sprint i lasts days[i] days. On day j of a sprint (counting from 1 within that sprint), finishing that day's work earns j points. So a 4-day sprint is worth 1, 2, 3, 4 on its four days.
The program is cyclic: when the last sprint ends, sprint 0 starts again, and this repeats forever.
You will train for exactly k consecutive days. You may start on any day of any sprint, and the run may wrap from the last sprint into the next loop. Return the maximum total points you can earn.
Implement:
def max_sprint_points(days: list[int], k: int) -> int: ...
Constraints
1 <= n <= 10^51 <= days[i] <= 10^91 <= k < sum(days)- Sprint lengths can be large, so a solution that walks day by day is too slow.
Example 1
days = [3, 1, 4], k = 5. One loop earns 1 2 3 | 1 | 1 2 3 4. The best run of 5 days takes the last two days of sprint 2 (3, 4) and then all of sprint 0 in the next loop (1, 2, 3), for 13.
Example 2
days = [2, 5], k = 3. The best run is the last three days of the 5-day sprint, 3 + 4 + 5 = 12.
Clarifying questions
- Since
k < sum(days), can the run wrap at most once? - Do the points restart at 1 at the start of each sprint, even after a wrap? (Yes.)
- Can the total exceed 64 bits? (Yes: one sprint of
10^9days is already worth about5 * 10^17points.) - Should we return the start day too?
What a strong answer covers
- Proves that some best run ends on the last day of a sprint. Within a sprint, the day values only grow, so shifting the window toward the sprint's end never loses.
- Doubles the sprint list to handle the wrap.
- Keeps prefix sums of days and of full-sprint points, using
L x (L + 1) / 2for a sprint of lengthL. - For each sprint end, finds where a run of
kdays starts with binary search or two pointers. It takes whole sprints plus the last days of one partial sprint, whose points are an arithmetic series. - That is O(n log n) or O(n). Tests both examples,
ksmaller than one sprint,kcovering all but one day, and one huge sprint.
Follow-ups
-
klarger than one full loop. - Return the start sprint and day.
- Day
jof a sprint earns some other function ofj. - Answer many values of
k.
Where it's asked
What it tests
Sign in to see the worked answer
The full answer, chapter by chapter, with what interviewers expect at each level. New accounts get 5 credits: each one unlocks a question for good.
What the labs asked this week
A weekly email of what OpenAI, Anthropic and the other top AI labs asked engineers, round by round.
Sign in to submit your code; every attempt is kept here.
