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

## Analysis

参考：<https://leetcode.com/problems/range-sum-query-immutable/solution/>

重点在于`sumRange()` 需要较高的效率，比如O(1)的时间复杂度。因此在初始化时要进行处理，最直觉的就是关于range sum，可以新建数组存入`[0, i)`的`sums`，这样需要`[i, j]`的时候，`sums[j + 1] - sums[i]`即可。小技巧是生成nums.length + 1的sums\[]，而`sums[i]`代表了`[0, i)`，也就是不包含`i`的和。

## Solution

```java
class NumArray {
    private int[] sums;
    public NumArray(int[] nums) {
        if (nums.length == 0) return;
        sums = new int[nums.length];
        sums[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            sums[i] = sums[i - 1] + nums[i];
        }
    }

    public int sumRange(int i, int j) {
        if (i == 0) return sums[j];
        return sums[j] - sums[i - 1];
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://aaronice.gitbook.io/lintcode/dynamic_programming/range-sum-query-immutable.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
