Created
August 13, 2023 11:54
-
-
Save Phryxia/b493e373f2610bf054f8e11f3404c105 to your computer and use it in GitHub Desktop.
TypeScript implementation of fast cumulative sum
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CumulativeSum { | |
private sums: number[] = [0]; | |
constructor(itr: Iterable<number>) { | |
const values = [...itr]; | |
for (let i = 0; i < values.length; ++i) { | |
this.sums[i + 1] = this.sums[i] + values[i]; | |
} | |
} | |
get(from: number, to: number) { | |
if (to < 0) return 0; | |
from = Math.max(from, 0); | |
to = Math.min(to, this.sums.length - 2); | |
return this.sums[to + 1] - this.sums[from]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment