Dynamic Programming21 sections · 916 units
Open in Course

Intro

The Goal

You have an array. Someone asks you: "What's the sum from index 3 to index 7?" Easy, you loop and add. But what if they ask 100,000100{,}000 such questions? Looping each time gives you O(nq)O(n \cdot q) where qq is the number of queries.

With n=100,000n = 100{,}000 and q=100,000q = 100{,}000, that's 1010 billion operations. Your program times out. By the end, you'll answer each query in O(1)O(1) time after a single O(n)O(n) preprocessing step. The technique is called prefix sums.