← Questions

Best k-day run in a cyclic sprint schedule

0
AmazonCoding

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^5
  • 1 <= days[i] <= 10^9
  • 1 <= 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^9 days is already worth about 5 * 10^17 points.)
  • 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) / 2 for a sprint of length L.
  • For each sprint end, finds where a run of k days 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, k smaller than one sprint, k covering all but one day, and one huge sprint.

Follow-ups

  • k larger than one full loop.
  • Return the start sprint and day.
  • Day j of a sprint earns some other function of j.
  • Answer many values of k.

Where it's asked

What it tests

prefix sums · sliding window · math · greedy

Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding