Dynamic Programming21 sections · 916 units
Open in Course

Static Range Sum Queries - Problem Statement

Query range sums fast

Given an array of nn integers and q queries, each query asks: what's the sum of elements from index a to b? The naive approach loops through a to b for each query. With n, q up to 200,000200{,}000, that's too slow. You just learned prefix sums.

This problem is the direct application. Can you see how to answer each query in O(1)O(1)? Build pref[i] = pref[i-1] + a[i], then answer each query with pref[r] - pref[l-1].