Prefix Sum
Pre-calculate and store the sum of elements from the start of the array to the current element.
Goal
Pre-calculate and store the sum of elements from the start of the array to the current element.
Plan
Create an integer array with the same size n
, storing the sum at each element.
Idea
- Initialize an array
prefix
with sizen
- Initialize
sum = 0
- For each element of index
i
in the range [0, n-1]:- Add the element to
sum
. - Store
sum
into theprefix
array at indexi
- Add the element to
Java Code
1
2
3
4
5
6
int sum = 0;
int[] prefix = new integer[n];
for (int i = 0; i < n; i++) {
sum += nums[i];
prefix[i] = sum;
}
Recommended reads
https://usaco.guide/silver/prefix-sums?lang=cpp
Interesting properties
- If two prefix sum have the same remainder when divided by
k
, then the subarray between them is divisible byk
.
Problems
https://www.hackerrank.com/challenges/k-subarrays/problem
This post is licensed under CC BY 4.0 by the author.
Comments powered by Disqus.