Batches That Split Evenly
Medium · Prefix Sums · about 25 min
A bakery tracks the change in its stock of rolls for each hour in nums (negative means more were sold than baked). A run of consecutive hours is a good batch when its total change can be packed into boxes of k with nothing left over, which means the total is divisible by k (0 counts, and so do negative multiples like -6 for k = 3).
Return how many non-empty contiguous runs of hours are good batches.
numshas 0 to 200,000 whole numbers, which can be negative or zero.kis a whole number from 1 to 10,000.
Example:
count_even_split_batches([3, 1, -4, 2, 5], 3) → 4 (the runs [3], [3, 1, -4], [1, -4] and [-4, 2, 5])
Hints
- Write the total of a run as the difference of two running totals.
- The difference of two numbers is divisible by k exactly when they have the same remainder.
- Count remainders in a map. In JavaScript, make negative remainders positive before you use them.
Learn the pattern first: the Prefix Sums lesson.
More Prefix Sums problems
- Where the Seesaw Balances (Easy)
- Stretches That Hit the Goal (Medium)
- Orchard Plot Totals (Medium)
- Plots With an Exact Harvest (Hard)