Fill the blank
Fill the blank so each query is O(1).
from itertools import accumulate
sales = [3, 1, 4, 1, 5]
prefix = [0, *accumulate(sales)]
l, r = 1, 3
print(____)Choose an answer, then open Show answer below to check it.
Show answer
Answer: A prefix[r + 1] - prefix[l]
Right: everything up to day r, minus everything before day l.
Days 1 to 3 hold 1, 4 and 1; the prefix difference gives that total with one subtraction.
Why not the others?
- B prefix[r] - prefix[l]. That stops one day short and misses day r.
- C sum(sales[l:r]). Correct only for the half-open range and still O(n) per query.