Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit e5e12e3

Browse files
Range Sum Query - Immutable
1 parent b30b57c commit e5e12e3

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
'''Leetcode- https://leetcode.com/problems/range-sum-query-immutable/ '''
2+
'''
3+
Given an integer array nums, handle multiple queries of the following type:
4+
5+
Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
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 inclusive (i.e. nums[left] + nums[left + 1] + ... + nums[right]).
10+
11+
12+
Example 1:
13+
14+
Input
15+
["NumArray", "sumRange", "sumRange", "sumRange"]
16+
[[[-2, 0, 3, -5, 2, -1]], [0, 2], [2, 5], [0, 5]]
17+
Output
18+
[null, 1, -1, -3]
19+
20+
Explanation
21+
NumArray numArray = new NumArray([-2, 0, 3, -5, 2, -1]);
22+
numArray.sumRange(0, 2); // return (-2) + 0 + 3 = 1
23+
numArray.sumRange(2, 5); // return 3 + (-5) + 2 + (-1) = -1
24+
numArray.sumRange(0, 5); // return (-2) + 0 + 3 + (-5) + 2 + (-1) = -3
25+
'''
26+
27+
class NumArray:
28+
29+
def __init__(self, nums):
30+
self.sums = nums[:]
31+
for i in range(1, len(self.sums)):
32+
self.sums[i] = self.sums[i-1] + nums[i]
33+
34+
def sumRange(self, left: int, right: int):
35+
if left == 0:
36+
return self.sums[right]
37+
else:
38+
return self.sums[right] - self.sums[left-1]
39+
40+
41+
42+
#T:O(n)
43+
#S:O(n)

‎README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,3 +25,5 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
2525
- [x] [Dynamic Programming](Dynamic-Programming)
2626
- [x] [Climbing Stairs](Dynamic-Programming/70-Climbing-Stairs.py)
2727
- [x] [Maximum Subarray](Dynamic-Programming/53-maximum-subarray.py)
28+
- [x] [Range Sum Query - Immutable](Dynamic-Programming/303-Range-Sum-Query-Immutable.py)
29+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /