Skip to content

Commit 180b28f

Browse files
authored
Fix pre-commit and ruff errors
1 parent 463e6aa commit 180b28f

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

dynamic_programming/prefix_sum.py

+12-7
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
"""
22
Author : Sanjay Muthu <https://github.com/XenoBytesX>
33
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.
55
66
The problem statement is:
77
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)
99
1010
Example:
1111
arr = [1, 4, 6, 2, 61, 12]
@@ -51,9 +51,14 @@
5151
==> [4, 6, 7, 13, 16]
5252
If the query was l=3, r=4,
5353
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]
5762
"""
5863

5964
from __future__ import annotations
@@ -71,14 +76,14 @@ def prefix_sum(array: list[int], queries: list[tuple[int, int]]) -> list[int]:
7176
dp = [0] * len(array)
7277
dp[0] = array[0]
7378
for i in range(1, len(array)):
74-
dp[i] = dp[i - 1] + array[i]
79+
dp[i] = dp[i-1] + array[i]
7580

7681
# Read Algorithm section (Line 38)
7782
result = []
7883
for query in queries:
7984
res = dp[query[1]]
8085
if query[0] != 0:
81-
res -= dp[query[0] - 1]
86+
res -= dp[query[0]-1]
8287
result.append(res)
8388

8489
return result

0 commit comments

Comments
 (0)