Lesson contents

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.

Start2 5 3
Result8
lesson.cpp
#include <iostream>

int main() {
    int sales[] = {2, 5, 3};
    int totals[] = {0, 0, 0, 0};
    int i = 0;
    while (i < 3) {
        totals[i + 1] = totals[i] + sales[i];
        i += 1;
    }
    std::cout << totals[3] - totals[1] << '\n';
}
Output
8
Advertisements

Everyday examples

Count riders over two stops

Boardings are 4, 3 and 6. How many boarded at stops two and three?

Start0 4 7 13
Result9

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?

Start11→16
Result5

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?

Start0 2 7
Result0 3 8

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.