Question:
How to measure the peak of an element using C++

Summary

It is an implementation of the peakElement function, whose goal is to locate any peak element in the input array. An element that is greater than or equal to its neighboring elements is referred to as a peak element.


Solutions

/* The function should return the index of any

   peak element present in the array */


// arr: input array

// n: size of array

class Solution

{

    public:

    int peakElement(int arr[], int n)

    {

       // Your code here

       if(n==1)

       return 0;

       for(int i=0;i<n;i++){

           if(i==0 && arr[i]>=arr[i+1])

           return i;

           

           else if(i==n-1 && arr[i]>=arr[i-1])

           return i;

           

           else{

           if(arr[i]>=arr[i-1]&&arr[i]>=arr[i+1]&&i>0)

           return i;

           }

       }

       return -1;

    }

};


Explanation

  • Two parameters are passed to the function peakElement: an integer array called arr and an integer called n, which is the array's size.

  • The code first determines whether the array contains a single element (if(n==1)). If so, it returns index 0 because the single element is by default regarded as a peak.

  • After that, a loop goes through each array element one by one. 


Answered by:> >22bceybpy

Credit:> >GeekforGeeks


Suggested blogs:

>Find the subsequences of string in lexicographically sorted order in C++

>How to detect whether the linked list has a loop using Java

>How to determine the number of valid groupings for a string using Java

>How to mock a constant value in Python?

>Creating a pivot table by 6 month interval rather than year

>How to Install mariaDB client efficiently inside docker?

>Can I call an API to find out the random seed in Python `hash()` function?

>How remove residual lines after merge two regions using Geopandas in python?


Submit
0 Answers