Dynamic Programming21 sections · 916 units
Open in Course

Naive Approach

Loop every query

The naive solution looks like this: For each query (l,r)(l, r), loop from ll to rr and sum the elements. Simple and correct, but slow. If n=105n = 10^5 and q=105q = 10^5, you're doing up to 101010^{10} operations. Most judges give you about 10810^8 operations per second.

Your code would take 100 seconds. Time limit is usually 1-2 seconds. The problem isn't its correctness. It's the repeated work. Every query recomputes sums from scratch. What if you precomputed something useful?