[leetcode] problem 303 – 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

  1. You may assume that the array does not change.
  2. There are many calls to sumRange function.

Code

1
2
3
4
5
6
7
8
9
10
11
12
private int[] sum;

public (int[] nums) {
sum = new int[nums.length + 1];

for (int i = 0; i < nums.length; i++)
sum[i + 1] = sum[i] + nums[i];
}

public int sumRange(int i, int j) {
return sum[j + 1] - sum[i];
}