Reputation: 2924
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.
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
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
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