Skip to main content

Prefix Sum

Prefix Sum - Starting with first element

vector<int> pref(n);
pref[0] = a[0];
for (int i = 1; i < n; i++) {
pref[i] = pref[i - 1] + a[i];
}

Prefix Sum - Starting with 0

vector<int> pref(n + 1);
for (int i = 0; i < n; i++) {
pref[i + 1] = pref[i] + a[i];
}

Suffix Sum - Starting with last element

vector<int> suff(n);
suff[n - 1] = a[n - 1];
for (int i = n - 2; i >= 0; i--) {
suff[i] = suff[i + 1] + a[i];
}

Suffix Sum - Starting with 0

vector<int> suff(n + 1);
for (int i = n - 1; i >= 0; i--) {
suff[i - 1] = suff[i] + a[i];
}