I want to calculate a rolling maximum and minimum value efficiently. Meaning anything better than recalculating the maximum/minimum from all the values in use every time the win
I'm assuming that by "window" you mean a range a[start]
to a[start + len]
, and that start
moves along. Consider the minimal value, the maximal is similar, and the move to the window a[start + 1]
to a[start + len + 1]
. Then the minimal value of the window will change only if (a) a[start + len + 1] < min
(a smaller value came in), or (b) a[start] == min
(one of the smallest values just left; recompute the minimum).
Another, possibly more efficient way of doing this, is to fill a priority queue with the first window, and update with each value entering/leaving, but I don't think that is much better (priority queues aren't suited to "pick out random element from the middle" (what you need to do when advancing the window). And the code will be much more complex. Better stick to the simple solution until proven that the performance isn't acceptable, and that this code is responsible for (much of) the resource consumption.