Prefix sums
Keep a running total at each boundary. The difference between two boundary totals gives the sum of the items between them.
Simple example
Boundary totals are 0, 2, 7 and 10. Subtract 2 from 10 to find the sum of the last two items.
fun main() {
var sales = intArrayOf(2, 5, 3)
var totals = intArrayOf(0, 0, 0, 0)
var i = 0
while (i < 3) {
totals[i + 1] = totals[i] + sales[i]
i += 1
}
println(totals[3] - totals[1])
}
8
Everyday examples
Count riders over two stops
Boardings are 4, 3 and 6. How many boarded at stops two and three?
Subtract the total before stop two, 4, from the total after stop three, 13.
Find a single day’s sales
Cumulative sales rise from 11 to 16 across Tuesday. What did Tuesday contribute?
Subtract consecutive boundary totals to recover that day’s amount.
Correct an old delivery
Deliveries are 2 and 5. The first delivery was actually 3. Which totals change?
Increase every boundary after the first delivery by one. The starting zero stays fixed.
Cost and limits
Building totals takes O(n) time. Each range sum then takes O(1). Changing one early item affects every following boundary.