## MatLab APP

Given an array of integers. Find all peak elements in it. An array element is peak if it is NOT smaller than its neighbors.The peak value is defined as the local maxima (or you can say peak element is the element which is greater than or equal to both of its neighbours.)
For corner elements, we need to consider only one neighbor.

NOTE:

If array has all the same elements, every element is a peak element.

Every array has a peak element.

For example, for input array {5, 10, 20, 15}, 20 is the only peak element.

For input array {10, 20, 15, 2, 23, 90, 67}, there are two peak elements: 20 and 90.

For example, x= [1 12 3 2 7 0 3 1 19 7]; peaks = [12 7 3 19];

MATLAB CODE:

clc
x=input('Enter the array:');
Y=[];
df=0;
for i=1:length(x)-1
m=x(i);
n=x(i+1);
if(m~=n)
df=df+1;
end
end
if(df==0)
disp('All elements are peak elements');
else

for i=1:length(x)
if(i==1)
m=x(1);
n=x(2);
if(m>=n)
Y=[Y m];
end
elseif(i==length(x))
m=x(length(x));
n=x(length(x)-1);
if(m>=n)
Y=[Y m];
end
else
m=x(i);
n=x(i-1);
k=x(i+1);
if(m>=n && m>=k)
Y=[Y m];
end
end
end
disp(Y);
end

Explanation:

OUTPUT:

JAVA CODE:

import java.util.Scanner;
class Humba
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("Enter the array length");
int l=obj.nextInt();
int a[]=new int[l];
System.out.println("Enter the element:");
for(int i=0;i<l;i++)
{
a[i]=obj.nextInt();
}
int m=0;
int n=0;
int k=0;
int b=0;
int c=0;
int d=0;
for(int i=0;i<l-1;i++)
{
b=a[i];
c=a[i+1];
if(b!=c)
{
d=d+1;
}
}
if(d==0)
{
System.out.println("All the elements are same");
}
else
{
for(int i=0;i<l;i++)
{
if(i==0)
{
m=a;
n=a;
if(m>=n)
System.out.println("Peak element found at index"+"["+i+"]"+"="+m);

}
else if(i==a.length-1)
{
m=a[l-1];
n=a[l-2];
if(m>=n)
System.out.println("Peak element found at index"+"["+i+"]"+"="+m);

}
else
{
m=a[i];
n=a[i-1];
k=a[i+1];
if(m>=n && m>=k)
System.out.println("Peak element found at index"+"["+i+"]"+"="+m);

}

}
}

}
}
OUTPUT:

You can check with other inputs :-)