John Doe
John Doe

Reputation: 2924

Find the local maxima in a sequence of values

What algorithm can we use to find the local maxima in a randomly generated value array of length 10?

My current strategy is to break the array into 3 and find the maximum element of each subset array, but that does not include all the maxima.

Line graph

Ideally, I would like the first point to also be identified as a local maximum, and the third red from left should not be marked as such.

Upvotes: 2

Views: 2395

Answers (2)

Bernhard Barker
Bernhard Barker

Reputation: 55609

Just go through all the indices and compare that element to the two elements on either side, skipping the check if it's on the edge.

Pseudo-code:

for each index
  if     (index == 0              or array[index-1] < array[index])
     and (index == array.length-1 or array[index+1] < array[index])
  {
    store index
  }

Upvotes: 8

Ivaylo Strandjev
Ivaylo Strandjev

Reputation: 70929

To find local maximae usually you can use hill climbing. Additionally you could improve it by applying simulated annealing to avoid stopping at a local maximum instead of a bigger maximum after it.

Upvotes: 2

Related Questions