File tree 1 file changed +4
-2
lines changed
1 file changed +4
-2
lines changed Original file line number Diff line number Diff line change 36
36
37
37
Algorithm:
38
38
So, first we calculate the prefix sum (dp) of the array.
39
- The prefix sum of the index i is the sum of all elements indexed from 0 to i (inclusive).
39
+ The prefix sum of the index i is the sum of all elements indexed
40
+ from 0 to i (inclusive).
40
41
The prefix sum of the index i is the prefix sum of index (i - 1) + the current element.
41
42
So, the state of the dp is dp[i] = dp[i - 1] + a[i].
42
43
51
52
If the query was l = 3, r = 4,
52
53
the answer would be 6 + 3 = 9 but this would require O(r - l + 1) time ≈ O(N) time
53
54
54
- If we use prefix sums we can find it in O(1) by using the formula prefix[r] - prefix[l - 1].
55
+ If we use prefix sums we can find it in O(1) by using the formula
56
+ prefix[r] - prefix[l - 1].
55
57
This formula works because prefix[r] is the sum of elements from [0, r]
56
58
and prefix[l - 1] is the sum of elements from [0, l - 1],
57
59
so if we do prefix[r] - prefix[l - 1] it will be
You can’t perform that action at this time.
0 commit comments