Leetcode
Dynamic Programming
303 Range Sum Query - Immutable

1. Question

Given an integer arraynums, find the sum of the elements between indicesiandj(i≤j), inclusive.
Example:
1
Given nums = [-2, 0, 3, -5, 2, -1]
2
3
sumRange(0, 2) -> 1
4
sumRange(2, 5) -> -1
5
sumRange(0, 5) -> -3
Copied!
Note:
  1. 1.
    You may assume that the array does not change.
  2. 2.
    There are many calls to sumRange function.

2. Implementation

(1) DP
1
class NumArray {
2
int prefixSum[];
3
public NumArray(int[] nums) {
4
int n = nums.length;
5
prefixSum = new int[n + 1];
6
7
for (int i = 1; i <= n; i++) {
8
prefixSum[i] = prefixSum[i - 1] + nums[i - 1];
9
}
10
}
11
12
public int sumRange(int i, int j) {
13
return prefixSum[j + 1] - prefixSum[i];
14
}
15
}
16
17
/**
18
* Your NumArray object will be instantiated and called as such:
19
* NumArray obj = new NumArray(nums);
20
* int param_1 = obj.sumRange(i,j);
21
*/
Copied!

3. Time & Space Complexity

DP: 时间复杂度: NumArray(): O(n), sumRange(): O(1), 空间复杂度O(n)