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

The algorithm is simple. Find all local maxima, for some appropriate definition of a maximum (eg, $_[0] < $_[1] > $_[2] might mean that $_[1] qualifies). Sort that list of maxima by value in descending order. Return the first k entries in the list.

so ...

my @values = qw(1 4 3 2 5 6 3 4 2); my @maxima = (); my $k = 2; foreach my $index (1 .. $#values - 1) { push @maxima, $values[$index] if( $values[$index-1] < $values[$index] && $values[$index+1] < $values[$index] ); } # @maxima now contains qw(4 6 4); print join(', ', (sort { $a <=> $b } @maxima)[0 .. $k - 1])."\n";
Finding the indices of the top k maxima is left as a trivial exercise for the reader (hint: push a structure onto @maxima containing the value and index).

Replies are listed 'Best First'.
Re^2: finding local minima/maxima for a discrete array
by ysth (Canon) on Aug 01, 2007 at 07:25 UTC
    That's a little oversimplified. In the case of 1 2 2 1, 2 is a local maximum. In 3 2 2 3, 2 is a local minimum. In 1 2 2 3, it's neither. You can't tell them apart just looking at the adjacent elements.