Editor

Shortest Stretch Worth at Least K

#477 · Sliding window · Expert · 250 XP · about 45 min

A game logs the points a player wins or loses in each round, and points[i] is the score of round i (negative for a round that cost points). Write shortest_at_least(points, k) that returns the length of the shortest stretch of consecutive rounds (at least one round) whose total is at least k, or -1 if no stretch reaches k.

Examples

shortest_at_least([3, -2, 4], 5)               # returns 3
shortest_at_least([1, 2], 4)                   # returns -1
shortest_at_least([4, -6, 3, 2, -1, 5], 6)     # returns 3

In the last example the rounds 2, -1 and 5 add up to 6. No two neighbouring rounds add up to 6 or more.

Constraints

  • 0 <= len(points) <= 100,000
  • -10^5 <= points[i] <= 10^5
  • 1 <= k <= 10^9

Note

The usual sliding window, which shrinks from the left while the total is big enough, breaks down here: because of the negative rounds, a longer stretch can be worth less than a shorter one inside it.

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.