# 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.

# Solution

Approach 1: Caching.

# Code (Python)

Approach 1:

class NumArray:

    def __init__(self, nums: List[int]):
        self.sums = [0]
        for num in nums:
            self.sums.append(self.sums[-1] + num)

    def sumRange(self, i: int, j: int) -> int:
        return self.sums[j+1] - self.sums[i]

# Code (C++)

Approach 1:

class NumArray {
private:
    vector<int> sum;
public:
    NumArray(vector<int> nums) {
        int tmp = 0;
        for (int i = 0; i < nums.size(); ++i)
        {
            tmp += nums[i];
            sum.push_back(tmp);
        }
    }
    
    int sumRange(int i, int j) {
        if (i > 0)
            return sum[j] - sum[i-1];
        else
            return sum[j];
    }
};
/**
 * Your NumArray object will be instantiated and called as such:
 * NumArray obj = new NumArray(nums);
 * int param_1 = obj.sumRange(i,j);
 */