I recently faced the similar problem on a programming website but there was another important constraint other than finding peaks. Firstly, there can be multiple peaks, but there can also be plateaus! A plateau is something that occurs in an arr: [1,2,2,2,1] and in this case we have to return the peak to be 2. In the problem we are also asked to return the first position where the peak occurs, so in this case it will be position = 1. The only case, that we have to remain careful about is that in arr: [1,2,2,2,3,4,5,1], there is peak with 5 in the second last position but there is no plateau even if there is a series of duplicates which look like a plateau in the first glance.
So the basic algorithm that I thought about was using a difference array as already suggested using {1,0,-1} where we use 0 when we get a series of duplicates in a continuous stream. Whenever we get a 0 while checking the difference array, we start looking for the first non zero entry, whether it is 1 or -1 and output accordingly. But again we have to remain careful that may be the Difference array looks like Diff = [-1,1,-1,1,0,0,0], in which case there is no plateau and only one peak. The python code looks like the following, when arr is given as input:
n = len(arr)
if arr == []:
return {"pos":[],"peaks":[]}
Diff = []
for i in range(0,n-1):
if arr[i]< arr[i+1]:
Diff.append(1)
elif arr[i] == arr[i+1]:
Diff.append(0)
if arr[i] > arr[i+1]:
Diff.append(-1)
pos = []
peaks = []
j = 0
for i in range(0,n-2):
if Diff[i] == 1 and Diff[i+1] == -1:
pos.append(i+1)
peaks.append(arr[i+1])
if Diff[i] == 1 and Diff[i+1] == 0:
if Diff[i+1:] == [Diff[i+1]]:
break
j = i+1
while(Diff[j] == 0 and j < n-2):
j = j+1
if Diff[j] == -1:
pos.append(i+1)
peaks.append(arr[i+1])
return {"pos":pos, "peaks":peaks}
0 0 0 42 0 0 0 0 0 0 0
your strategy fails and there is no constraint that elements can't be equal (even example in your post has two1
s). – Sulfa