Skip to content

Commit d70bb94

Browse files
committed
Added 0303-range-sum-query-immutable.cpp
Signed-off-by: Al Asad Nur Riyad <[email protected]>
1 parent 92ec5e7 commit d70bb94

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Diff for: cpp/0303-range-sum-query-immutable.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
Given an integer array nums, handle multiple queries of the following type:
3+
4+
Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
5+
6+
Implement the NumArray class:
7+
8+
- NumArray(int[] nums) Initializes the object with the integer array nums.
9+
- int sumRange(int left, int right) Returns the sum of the elements of nums between indices left and right
10+
inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).
11+
12+
*/
13+
14+
15+
class NumArray {
16+
public:
17+
vector<int> prefixSum;
18+
NumArray(vector<int>& nums) {
19+
int count=0;
20+
for(int i=0;i<nums.size();i++){
21+
count+=nums[i];
22+
prefixSum.push_back(count);
23+
}
24+
}
25+
26+
int sumRange(int left, int right) {
27+
int answer=prefixSum[right];
28+
29+
if(left-1>=0){
30+
answer-=prefixSum[left-1];
31+
}
32+
return answer;
33+
}
34+
};
35+
36+
/**
37+
* Your NumArray object will be instantiated and called as such:
38+
* NumArray* obj = new NumArray(nums);
39+
* int param_1 = obj->sumRange(left,right);
40+
*/

0 commit comments

Comments
 (0)