March 3rd, 2011, 10:32 pm
Here's one possible approach that should average O(log(n)) for most sequences. I've not tried it so you might want to ponder it carefully before taking my word that it works. Perhaps one trick is to remove all incoming values that will never be a maximum in any [q,now] window. For example, if X[now] > X[now-1], then the X[now-1] value will never be the maximum in any [q,now] interval. Thus, you can cull low values that can't be maxima from a list of candidate values as they come in. You could build a double-ended list where each element stores an (X[timestamp],timestamp) pair of candidate maxima. On this List, the first item is the oldest item on the list and the last item is the most recent candidate maximum value on the list.Manage the list:1. IF time stamp on the first_item > T THEN Delete First_Item2. IF X[now] > X[Last_Item], THEN delete Last_Item and repeat step 23. append (X[now],now) to listThis list manager creates and manages a data structure of potential candidate maxima in [T,now]. It will contain a monotonically non-increasing list of values with their corresponding monotonically-increase timestamps (assuming now>T). Step 2 of the algorithm could be O(n) worst case, but only in the bizarre case where X is steadily falling and then one gets a massive jump with a new X that's higher than any X in the entire [T,now] range. (For extra credit, one might be able to construct a better search algo for step 2 but I doubt it would be worth it for most semi-random time series)To find the maximum value in a [q,now] window, do a bisection search on the list looking for the element with last timestamp within the [q,now] range and that will be the answer. That search should be O(log(n))Duplicate the above logic for the minima with the value-comparison conditionals appropriately reversed. EDIT: Making the conditional in step 2 a "≥" instead of ">" will improve performance somewhat although it also means the algorithm will report the most recent timestamp if two data points are tied for highest value (the version with ">" would report the older timestamp in the case of a tie).
Last edited by
Traden4Alpha on March 3rd, 2011, 11:00 pm, edited 1 time in total.