Given an integer array nums, handle multiple queries of the following type:
nums between indices left and right inclusive where left <= right.Implement the NumArray class:
NumArray(int[] nums) Initializes the object with the integer array nums.int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).Input
["NumArray", "sumRange", "sumRange", "sumRange"]
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
Output
[null, 1, -1, -3]
Explanation
104 calls will be made to sumRange.The simplest way to solve this problem is to calculate the sum of elements from i to j every time a query is made.
i to j and sum up the elements.O(n) per query, where n is the number of elements in the range [i, j].O(1) for handling each query since no additional space is used other than input storage.A more optimal approach is to preprocess the input array to create a prefix sum array.
i stores the cumulative sum of the array from 0 to i.i to j, we can use the formula: [ \text{sumRange}(i, j) = \text{prefixSum}[j] - \text{prefixSum}[i-1] ]O(1).O(n) for preprocessing where n is the number of elements in the input array. O(1) for each sum range query.O(n) due to the prefix sum array.