If you must answer many "what is the sum of elements from index left to right?" questions, adding them up each time is O(n) per query. A prefix sum array lets you precompute once and answer each query in O(1).
A shop's ledger holds the net change in cash for each day, and the manager keeps asking the same kind of question: what was the total change from day left to day right? Write a class NumArray that answers these questions:
NumArray(nums): the constructor is handed the daily changes as a list of integers.sum_range(left, right): returnsnums[left] + nums[left+1] + ... + nums[right], counting both end days.
Examples
Input:
NumArray([4, -1, 6, -3, 2, 5])
sum_range(0, 2) -> 9 (4 - 1 + 6)
sum_range(2, 5) -> 10 (6 - 3 + 2 + 5)
sum_range(0, 5) -> 13
Constraints
1 <= len(nums) <= 10**40 <= left <= right < len(nums)- The constructor may do O(n) work; aim for O(1) per
sum_rangecall.
Goals
- Build a prefix-sum array in the constructor so queries become O(1)
- Express the sum of nums[left..right] as a difference of two prefix sums
- Handle the off-by-one at the left edge with a leading 0