-
Notifications
You must be signed in to change notification settings - Fork 1k
/
Copy pathPeak_element.java
61 lines (58 loc) · 1.49 KB
/
Peak_element.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/*
An array element is a peak
if it is NOT smaller than its neighbours.
For corner elements, we need to consider only one neighbour.
*/
import java.util.Scanner;
public class peak_element
{
// Function to find the peak element
peak_element(int arr[], int length)
{
for(int i=0;i<=length;i++)
{
if(arr[i]==arr[0])
{
if(arr[i]>arr[i+1])
{
System.out.println("Peak value : "+arr[i]);
}
}
if(arr[i]==arr[length-1])
{
if(arr[i]>arr[length-2])
{
System.out.println("Peak value : "+arr[i]);
}
}
if(arr[i]>arr[i+1] && arr[i]>arr[i-1])
{
System.out.println("Peak value : "+arr[i]);
}
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter length of an array..");
int length=sc.nextInt();
System.out.println("your array please..");
int arr[]=new int[length];
for(int i=0;i<length;i++)
{
arr[i]=sc.nextInt();
}
peak_element obj=new peak_element(arr, length);
}
}
/*
Input--
Enter length of an array..
5
your array please..
2 5 8 9 5
Output--
Peak value : 9
Time Complexity : O(n)
Space Complexity : O(n)
*/