problem no 27: peak element in the array ,peak element is the one who is greater than the left as well as right element.
QUESION:
A peak element in an array is the one that is not smaller than its neighbours.
Given an array of size N, find the index of any one of its peak elements.
Example 1:
Input: N = 3 arr[] = {1,2,3} Output: 2 Explanation: index 2 is 3. It is the peak element as it is greater than its neighbour 2.
Example 2:
Input: N = 2 arr[] = {3,4} Output: 1 Explanation: 4 (at index 1) is the peak element as it is greater than its only neighbour element 3.
ANSWER:
int peakElement(int arr[], int n)
{
if(n==1)
{
return 0;
}
else
{
for(int i=0;i<n;i++)
{
if(i==0 || i==n-1)
{
if(i==0)
{
if(arr[i]>arr[i+1])
{
return i;
}
}
else if(i==n-1)
{
if(arr[i]>arr[i-1])
{
return i;
}
}
}
else
{
if((arr[i]>arr[i+1]) && (arr[i]>arr[i-1]))
{
return i;
}
}
}
}
}
Comments
Post a Comment