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:
- You may assume that the array does not change.
- There are many calls to sumRange function.
Subscribe to see which companies asked this question
Tags
Dynamic Programming
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Since there are many calls to sumRange function.
We need an array to save the results of the sum from 0 to n.
/**
* @constructor
* @param {number[]} nums
*/
var NumArray = function(nums) {
this.total = [];
var len = nums.length;
if(len === 0) {
return 0
}
this.total[0] = nums[0];
for(var i=1;i<len;i++) {
this.total[i] = this.total[i-1] + nums[i];
}
};
/**
* @param {number} i
* @param {number} j
* @return {number}
*/
NumArray.prototype.sumRange = function(i, j) {
if(i === 0) {
return this.total[j];
} else {
return this.total[j] - this.total[i-1];
}
};
/**
* Your NumArray object will be instantiated and called as such:
* var numArray = new NumArray(nums);
* numArray.sumRange(0, 1);
* numArray.sumRange(0, 2);
*/