Sunday, 12 September 2021

Find Peak Element

A peak element is an element that is greater than its neighbors.
Given an input array where num[i] ≠ num[i+1], find a peak element and return its index.
The array may contain multiple peaks, in that case return the index to any one of the peaks is fine.
You may imagine that num[-1] = num[n] = -∞.
For example, in array [1, 2, 3, 1], 3 is a peak element and your function should return the index number 2.
Approach: Use binary search.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
int peakIndex(int *arr, int low, int high){
    if(low == high){
        return low;
    }
    if(low + 1 == high){
        if(arr[low] >= arr[high]){
            return low;
        }else{
            return high;
        }
    }
    int mid = (low + high) / 2;
    if(arr[mid] > arr[mid - 1] && arr[mid] > arr[mid + 1]){
        return mid;
    }else if(arr[mid] < arr[mid - 1]){
        //peak lies on the left since arr[mid - 1] > arr[mid] && arr[0] = -infinity so there has to be an element which is peak on the left
        return peakIndex(arr, low, mid - 1);
    }else{
        //peak lies on the right
        return peakIndex(arr, mid + 1, high);
    }
}

int findPeakElement(int* nums, int numsSize) {
    return peakIndex(nums, 0, numsSize - 1);
}
Share:

5 comments:

  1. Our DevOps Training in Noida incorporates *online classes, classroom sessions, real-life case studies, develop and deploy software using DevOps* and lots more.

    ReplyDelete
  2. Get the best Python Training in Noida, ✓ state-of-the-art infrastructure, ✓ interactive classes, ✓ self-paced studies, and ✓ studies through real-life case studies.

    ReplyDelete
  3. Nice post. I was checking constantly this blog and I am impressed! Extremely helpful information specially the last part I care for such info a lot.

    Are you believing that a Mobile App Ideas is costly? The App Ideas is leading web and Mobile App development. We provide the best IT Services at best rates. Contact us now!

    ReplyDelete

Contact Me

Name

Email *

Message *

Popular Posts