ahmd0 - 5 months ago 37

C# Question

Say, if I had a final array of numbers, say:

`{1, 5, 7, 2}`

the average for them will be:

`(1 + 5 + 7 + 2) / 4; //Or, sum of all elements, divided by their number`

But what if my array is constantly growing and I need to know the current average number at an instance of time when the full array is not known yet. How do you calculate that?

Say, like when I'm trying to display current data transfer rate.

Answer

I would go with a simple approach for having a `running total`

(cumulative) with a constant space complexity (1). And on request of avg, return the result which is `running total/total number of item`

. No extended time complexity since we don't iterate array afterwards to find cumulative sum.