Check greatest element in the Neighbor in 1D Matrix of length N
Description
You are provided an array A which has N elements. Your task is to find the count of such occurrence where the element is larger than its neighbor.
Input
Input Format :
First line of input contains N which is the number of elements present in the array.
Second line contains N integer which are the elements of the array A.
Constraints :
N<100
There will always be at least 2 elements
Output
Output one integer which is the count of such occurrences
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int len = sc.nextInt();
int []arr = new int[len] ;
for (int i =0; i<len ;i++){
arr[i]=sc.nextInt();
}
int count=0;
for (int j = 0;j<len;j++){
if ( (j==0 && arr[0]>arr[1]) || ((arr[len-1]>arr[len-2]) && j==len-1) ){
count++;
}else if ((j!=0 && arr[j]>arr[j-1]) && (j!=len-1 && arr[j]>arr[j+1]) ){
count++;
}
} System.out.println(count);
}
}
No comments:
Post a Comment