-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEquiLeader.js
50 lines (37 loc) · 912 Bytes
/
EquiLeader.js
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
//Codility - EquiLeader Problem 100% Success
/*
https://app.codility.com/programmers/lessons/8-leader/equi_leader/
*/
function solution(A) {
if(A.length === 1){
return 0;
}
let map = {};
let max = -1;
let leader = null;
for(let i = 0; i < A.length; i++){
if(A[i] in map){
map[A[i]]++;
if(map[A[i]] > Math.floor(A.length / 2)){
max = map[A[i]];
leader = A[i];
}
}else{
map[A[i]] = 1;
}
}
if(max === -1){
return 0;
}
let leaderCount = 0;
let equiLeader = 0;
for(let i = 0; i < A.length -1; i++){
if((leaderCount > Math.floor(i / 2)) && (max - leaderCount > Math.floor((A.length - i) / 2))){
equiLeader++;
}
if(A[i] === leader){
leaderCount++;
}
}
return equiLeader;
}