-
Notifications
You must be signed in to change notification settings - Fork 3
/
MajorElement.java
50 lines (46 loc) · 1.24 KB
/
MajorElement.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
/******************************************************************************
Major Element-> element having more than n/2 occurrene in an array
*******************************************************************************/
import java.util.Scanner;
public class MajorElement
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] arr=new int[n];
for(int i=0; i<n; i++) {
arr[i]=sc.nextInt();
}
int maxElement=arr[0]; //initially let major element
int counter=1;
//check for possible major element
for(int i=1; i<n; i++) {
if(arr[i]==maxElement) {
counter++;
} else if(counter>0) {
counter--;
} else {
counter=1;
maxElement=arr[i];
}
}
int maxOccur=0;
if(counter>0) {
for(int element:arr) {
if(element==maxElement)
maxOccur++;
}
}
if(maxOccur>n/2) {
System.out.println("Major Element is: "+maxElement);
}else {
System.out.println(" No Major Element is");
}
}
}
//Input-1: 6
// 2 2 2 4 5 2
//Output-1: Major Element is: 2
//Input-2: 9
// 4 4 4 4 5 2 4 4 5
//Output-2: Major Element is: 4