FIRST PEAK ELEMENT in java

FIRST PEAK ELEMENT in java

An element is called a peak element if its value is not smaller than the value of its adjacent elements(if they exists). Given an array arr[] of size n, find the index of first peak element. If peak element does not exist print -1.

Input

line 1: contains an integer n denoting size of array.

line 2: contains n spaced integers denoting elements of array.

Output

Print a single integer denoting the index of first peak element in array. If no such element exists, print -1.

Constraints

1<=n<=10^6

1<=arr[i]<=10^6

Expected Time Complexity: O(N)

Expected Space Complexity: O(1)

Sample Input

3
1 2 3

Sample Output

2

Solution of FIRST PEAK ELEMENT :–

import java.util.*;
import java.lang.*;
import java.io.*;

public class Main
{
	public static void main (String[] args) throws java.lang.Exception
	{
		//your code here
      Scanner sc = new Scanner(System.in);
      int n = sc.nextInt();
      int arr[] = new int[n];
      int temp=-1;

      for(int i=0;i<n;i++)
        {
          arr[i]=sc.nextInt();
        }

      
        for(int i=0;i<n;i++)
        {
          
          if(i==0)
          {
            if(arr[i]>arr[i+1])
            {
              temp=i;
              break;
            }
          }
        else if(i==n-1)
        {
           if(arr[i]>arr[i-1])
            {
                temp=i;
                break;
            } 
        }
        else{
           if(arr[i]>arr[i-1] && arr[i]>arr[i+1])
           {
             temp=i;
             break;
            }
           }
          }
          System.out.println(temp);  
        }
      }

Add a Comment

Your email address will not be published. Required fields are marked *