I have an equation that is as such
cValues[i++] = (sum += d) / ++count;
but then the count can be limited by the window size if the count is greater than or equal to the window size so the equation has a potential to become
cValues[i++] = (sum += d) / windowSize;
The windowSize is constant. By my observation of this area, is O(n) then to O(1) when it hits the window size.
Also the space complexity I am guessing is O(n) as well.
the whole method is such:
double[] CMA(int windowSize, double[] values)
{
//size of array determined by user
double[] cValues = new double[values.Length];
//index
int i = 0;
foreach (var d in values)
{
if (count >= windowSize)
{
cValues[i++] = (sum += d) / windowSize;
}
else if (count < windowSize)
{
cValues[i++] = (sum += d) / ++count;
}
}
return cValues;
}
The values can be any types of doubles, negative or positive.
The answer to the question is that since we can have negatives, it is possible that we never surpass windowSize
, hence reaching count
is a perfectly possible scenario, so, in time this is O(n). In terms of space complexity, the whole function has O(n) as you have correctly understood it, but the actual algorithm, that is, the
foreach (var d in values)
{
if (count >= windowSize)
{
cValues[i++] = (sum += d) / windowSize;
}
else if (count < windowSize)
{
cValues[i++] = (sum += d) / ++count;
}
}
part does not allocate new elements. The initialization phase is responsible for your whole space complexity.