No such thing as a small change | |
PerlMonks |
Re: finding local minima/maxima for a discrete arrayby Anno (Deacon) |
on Jul 31, 2007 at 10:16 UTC ( [id://629787]=note: print w/replies, xml ) | Need Help?? |
...need to find the top k local maxima
ysth has shown a nice method to find local maxima in an array. I'd like to add that it isn't necessary to store (and sort) all maxima if only the top $k are needed. A heap data structure minimizes both time- and space requirements of the task. Assuming a mythical Heap class with methods new, insert, extract_min, and size, create a heap and then for each new local maximum $max: (This step can be optimized a little more.) After all are done, returns the top $k maxima (or as many as there are) in ascending order. CPAN has a couple of heap-implementations. In practice, quite often the expense of storing and sorting the full array is irrelevant, so the heap solution isn't often implemented. I still like to point out the alternative whenever a "top $k" problem comes up. Anno
In Section
Seekers of Perl Wisdom
|
|