Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re: finding local minima/maxima for a discrete array

by Anno (Deacon)
on Jul 31, 2007 at 10:16 UTC ( [id://629787]=note: print w/replies, xml ) Need Help??


in reply to finding local minima/maxima for a discrete array

...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

my $heap = Heap->new;
and then for each new local maximum $max:
$heap->insert( $max); $heap->extract_min if $heap->size > $k;
(This step can be optimized a little more.)

After all are done,

map $heap->extract_min, 1 .. $heap->size;
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

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://629787]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-24 10:53 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found