Skip to content

Instantly share code, notes, and snippets.

@renatoargh
Created October 28, 2018 18:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save renatoargh/58c14c7019311781145d8cf68069e66d to your computer and use it in GitHub Desktop.
Save renatoargh/58c14c7019311781145d8cf68069e66d to your computer and use it in GitHub Desktop.
sum: O(n), get sum of segment: O(1)
function prefixedSum(array) {
const sum = new Array(array.length + 1)
sum[0] = 0
for(let k = 1; k < sum.length; k++) {
sum[k] = (sum[k - 1] || 0) + array[k - 1]
}
return sum
}
function segmentSum(sum, x, y) {
return sum[y + 1] - sum[x]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment