1
1
"""
2
2
Author : Sanjay Muthu <https://github.com/XenoBytesX>
3
3
4
- This is an implementation of the Dynamic Programming solution to the Range Sum Query problem .
4
+ This is an implementation of the Dynamic Programming solution to the Range Sum Query.
5
5
6
6
The problem statement is:
7
7
Given an array and q queries,
8
- each query stating you to find the sum of elements l to r (inclusive) (l and r are given in the query)
8
+ each query stating you to find the sum of elements l to r (inclusive)
9
9
10
10
Example:
11
11
arr = [1, 4, 6, 2, 61, 12]
51
51
==> [4, 6, 7, 13, 16]
52
52
If the query was l=3, r=4,
53
53
The answer would be 6+3 = 9 but this would require O(r-l) time ≈ O(N) time
54
- If we use prefix sums we can find it in O(1) time by using the formula prefix[r]-prefix[l-1]
55
- This formula works because prefix[r] is the sum of elements from [0, r] and prefix[l-1] is the sum of elements from [0, l-1],
56
- so if we do prefix[r]-prefix[l-1] it will be [0, r] - [0, l-1] = [0, l-1] + [l, r] - [0, l-1] = [l, r]
54
+
55
+
56
+ If we use prefix sums we can find it in O(1) by using the formula prefix[r]-prefix[l-1]
57
+ This formula works because prefix[r] is the sum of elements from [0, r]
58
+ and prefix[l-1] is the sum of elements from [0, l-1],
59
+ so if we do prefix[r]-prefix[l-1] it will be [0, r] - [0, l-1]
60
+ = [0, l-1] + [l, r] - [0, l-1]
61
+ = [l, r]
57
62
"""
58
63
59
64
from __future__ import annotations
@@ -71,14 +76,14 @@ def prefix_sum(array: list[int], queries: list[tuple[int, int]]) -> list[int]:
71
76
dp = [0 ] * len (array )
72
77
dp [0 ] = array [0 ]
73
78
for i in range (1 , len (array )):
74
- dp [i ] = dp [i - 1 ] + array [i ]
79
+ dp [i ] = dp [i - 1 ] + array [i ]
75
80
76
81
# Read Algorithm section (Line 38)
77
82
result = []
78
83
for query in queries :
79
84
res = dp [query [1 ]]
80
85
if query [0 ] != 0 :
81
- res -= dp [query [0 ] - 1 ]
86
+ res -= dp [query [0 ]- 1 ]
82
87
result .append (res )
83
88
84
89
return result
0 commit comments