Question:
Given an array of integers, representing points in a graph, find all points which are the 'peak' points in a graph.
Arr: [ 1, 4, 3, -1, 5, 5, 7, 4, 8 ]
Peaks: [4, 7, 8]
If you plot the numbers in the array as a graph, you'll see it rising and falling based on the value. For a point to qualify as a 'peak', the graph should rise to the 'peak' and then fall, exceptions being the first and last elements. For the first element to be a peak, the graph should fall after it. For the last element to be a peak, the graph should rise before it.
Try to solve in O(n) time.
def find_peaks(a):
"""
i-1,i, i+1
i is peak if i> i-1 and i>i+1
"""
n = len(a)
peaks = []
if a[0] > a[1]:
peaks.append(a[0])
for i in range(1, n-1):
if a[i-1] < a[i] and a[i] > a[i+1]:
peaks.append(a[i])
if a[n-1] > a[n-2]:
peaks.append(a[n-1])
return peaks
I first had a while loop and within it I had i += 1. But later on decided to use for loop and range, but forgot to remove increment i statement and still after running it gave me right results. I think python ignores increment if range is used with for loop.
It takes care of plateau as well. Later on I found that following Solution is more appropriate to include first and last elements in the loop as well:
def findPeaks(a):
"""
i-1,i, i+1
i is peak if i> i-1 and i>i+1
"""
peaks = []
n = len(a)
for i in range(1,n-1):
if i == 0:
if a[i] > a[i+1]:
peaks.append(a[i])
elif i == n-1:
if a[i] > a[i-1]:
peaks.append(a[i])
else:
if a[i] > a[i-1] and a[i] > a[i+1]:
peaks.append(a[i])
return peaks