Range Sum Query - Immutable
描述
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.
Example:
Given nums = [-2, 0, 3, -5, 2, -1]
sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note:
- You may assume that the array does not change.
- There are many calls to sumRange function.
分析
令状态f[i]为0到i元素之间的和,则状态转移方程为 f[i] = f[i-1] + nums[i]。f[i]本质上是累加和,有了f[i],则范围[i,j]之间的和等于f[j] - f[i-1]。