Friends Of Appropriate Ages LeetCode solution in JavaScript

1
var numFriendRequests = function (ages) {
2
const count = new Array(121).fill(0);
3

4
ages.forEach((age) => count[age]++);
5

6
let res = 0; // total friend request sent
7
let tot = 0; // cumulative count of people so far
8

9
for (let i = 0; i <= 120; i++) {
10
if (i > 14 && count[i] != 0) {
11
const limit = Math.floor(0.5 * i) + 7;
12
const rest = tot - count[limit];
13

14
res += count[i] * rest; // current age group send friend request to other people who are within their limit
15
res += count[i] * (count[i] - 1); // current age group send friend request to each other
16
}
17

18
tot += count[i];
19
count[i] = tot;
20
}
21

22
return res;
23
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0