Algorithmic patterns · 8 / 15 Exercise Medium

Range sums with prefixes

Objective

If you store the prefix sums (the running sum up to each position), the sum of any range is obtained with a single subtraction: prefixes[right + 1] - prefixes[left].

Instructions

  • The first line has space-separated integers; the second, the number q of queries; then q lines left right (positions from 0, both included).
  • For each query show the sum of the elements from that position to that other one.
Input
3 1 4 1 5 9 2 6
2
0 7
2 4
Output
31
10

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise