If I have, lets say a vector with millions of elements and I keep being asked what is the sum of all elements of a slice of this vector, what data structure would be suitable for this task?
I could just iterate over the slice, but it seems like I'm wasting some previous calculations if I keep doing that all the time. If I calculate the sum for v[500_000..750_000]
and them calculate the sum of v[400_000..600_000]
there is an overlap between those, and it seems I could use some dynamic programing to reuse calculations.
There're many ways to approach your problem, which arises very frequently in programming. The data structures below are roughly sort in difficulty in ascending order. (Earlier means easier)
In general prefix sum should be the way to go for unless you need other functionality later on, because it's the most intuitive and efficient in terms of both memory and runtime. All of these also incorporate the concept of dynamic programming inside.