# 区间和的个数

<p>给你一个整数数组 <code>nums</code> 以及两个整数 <code>lower</code> 和 <code>upper</code> 。求数组中，值位于范围 <code>[lower, upper]</code> （包含 <code>lower</code> 和 <code>upper</code>）之内的 <strong>区间和的个数</strong> 。</p>

<p><strong>区间和</strong> <code>S(i, j)</code> 表示在 <code>nums</code> 中，位置从 <code>i</code> 到 <code>j</code> 的元素之和，包含 <code>i</code> 和 <code>j</code> (<code>i</code> ≤ <code>j</code>)。</p>

<p> </p>
<strong>示例 1：</strong>

<pre>
<strong>输入：</strong>nums = [-2,5,-1], lower = -2, upper = 2
<strong>输出：</strong>3
<strong>解释：</strong>存在三个区间：[0,0]、[2,2] 和 [0,2] ，对应的区间和分别是：-2 、-1 、2 。
</pre>

<p><strong>示例 2：</strong></p>

<pre>
<strong>输入：</strong>nums = [0], lower = 0, upper = 0
<strong>输出：</strong>1
</pre>

<p> </p>

<p><strong>提示：</strong></p>

<ul>
	<li><code>1 <= nums.length <= 10<sup>5</sup></code></li>
	<li><code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code></li>
	<li><code>-10<sup>5</sup> <= lower <= upper <= 10<sup>5</sup></code></li>
	<li>题目数据保证答案是一个 <strong>32 位</strong> 的整数</li>
</ul>


## template

```java
class Solution {
	public int countRangeSum(int[] nums, long lower, long upper) {
		long sums[] = new long[nums.length];
		for (int i = 0; i < nums.length; i++) {
			sums[i] = ((i - 1 >= 0) ? sums[i - 1] : 0) + nums[i];
		}

		int result = divideAndConquer(sums, 0, sums.length - 1, upper, lower);

		return result;
	}

	private int divideAndConquer(long sums[], int start, int end, long upper, long lower) {
		if (start > end)
			return 0;
		if (start == end)
			return (sums[start] <= upper && sums[start] >= lower) ? 1 : 0;
		int mid = (start + end) / 2;
		int counts = 0;
		counts += divideAndConquer(sums, start, mid, upper, lower);
		counts += divideAndConquer(sums, mid + 1, end, upper, lower);

		int ls = start, le = mid;
		while (le >= start && sums[mid + 1] - sums[le] <= upper)
			le--;
		for (int r = mid + 1; r <= end; r++) {
			while (ls <= mid && sums[r] - sums[ls] >= lower)
				ls++;
			while (le + 1 <= mid && sums[r] - sums[le + 1] > upper)
				le++;
			if (ls - le - 1 < 0)
				continue;
			counts += (ls - le - 1);
		}
		ls = start;
		int i = 0, r = mid + 1;
		long merged[] = new long[end - start + 1];
		while (ls <= mid || r <= end) {
			if (ls > mid || (r <= end && sums[r] < sums[ls])) {
				merged[i++] = sums[r++];
			} else {
				merged[i++] = sums[ls++];
			}
		}
		for (i = 0; i < merged.length; i++) {
			sums[start + i] = merged[i];
		}

		return counts;
	}
}

```

## 答案

```java

```

## 选项

### A

```java

```

### B

```java

```

### C

```java

```