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:

Peak element

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

Popular posts from this blog

problem 3: given two integers N and M. The problem is to find the number closest to N and divisible by M. If there are more than one such number, then output the one having maximum absolute value.

problem no 7:Given two numbers A and B, find Kth digit from right of AB.

Problem no 16: count the number of squares below N.