Gamified challenge · Prefix sums
deposits[i] is the net amount that moved on day i: positive for deposits, negative for withdrawals, 0 for a quiet day. A stretch is one or more consecutive days. Write countK(deposits, k) that returns how many stretches have a total of exactly k.
For deposits = [1, 2, 3] and k = 3 the answer is 2: the stretches [1, 2] and [3]. Different stretches count separately even if their days hold the same values, so [0, 0, 0, 0] with k = 0 has 10.
Because withdrawals can make the total go down, a sliding window doesn't work here; think about running totals.
This game is part of the paid plans. Sign in, then pick a plan to write your answer, watch it play out, and step through the algorithm with its guide.
Sign in with Google