Peak Element Solution

 In this post, i solved a array problem where i need to find the peek element from given array.

Solution:

Based on linear search we just need to traverse over the given list and try to find a index whoose number is greater than its both 

arr[indx] > arr[indx-1] and arr[indx] > arr[indx+1]

Note: in any case don't select any number which is less than any of its neighbour.

Python Solution:

 

def peakElement(self,arr, n):
        i = 1
        while i< n:
            if arr[i] > arr[i-1] and i+1 >= n:
                return i
            if arr[i] > arr[i-1] and arr[i] > arr[i+1]:
                return i
            i += 1
        if n>1 and arr[0] > arr[1]:
            return 0
        return 0

 

 

I solve this question using python, 

let me know in comment if any optimization required for this question. 


Post a Comment

0 Comments