-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathequiLeader.js
41 lines (36 loc) · 865 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
function solution(A) {
// find the leader of the orignal array
const N = A.length;
const stack = [];
for (let i = 0; i < N; i++) {
if (stack.length === 0 || stack[stack.length - 1] === A[i]) {
stack.push(A[i]);
} else {
stack.pop();
}
}
const leader = stack.pop();
let totalLeaderCount = 0;
for (let i = 0; i < N; i++) {
if (A[i] === leader) {
totalLeaderCount++;
}
}
// search for equi leaders
let equiLeaderCount = 0;
let leftLeaderCount = 0;
let rightLeaderCount = totalLeaderCount;
for (let i = 0; i < N; i++) {
if (A[i] === leader) {
leftLeaderCount++;
rightLeaderCount--;
}
if (
leftLeaderCount >= Math.floor((i + 1) / 2) + 1 &&
rightLeaderCount >= Math.floor((N - 1 - i) / 2) + 1
) {
equiLeaderCount++;
}
}
return equiLeaderCount;
}