|
| 1 | +/** |
| 2 | + * 825. Friends Of Appropriate Ages |
| 3 | + * https://leetcode.com/problems/friends-of-appropriate-ages/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * There are n persons on a social media website. You are given an integer array ages where ages[i] |
| 7 | + * is the age of the ith person. |
| 8 | + * |
| 9 | + * A Person x will not send a friend request to a person y (x != y) if any of the following |
| 10 | + * conditions is true: |
| 11 | + * - age[y] <= 0.5 * age[x] + 7 |
| 12 | + * - age[y] > age[x] |
| 13 | + * - age[y] > 100 && age[x] < 100 |
| 14 | + * |
| 15 | + * Otherwise, x will send a friend request to y. |
| 16 | + * |
| 17 | + * Note that if x sends a request to y, y will not necessarily send a request to x. Also, a person |
| 18 | + * will not send a friend request to themself. |
| 19 | + * |
| 20 | + * Return the total number of friend requests made. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {number[]} ages |
| 25 | + * @return {number} |
| 26 | + */ |
| 27 | +var numFriendRequests = function(ages) { |
| 28 | + const ageCount = new Array(121).fill(0); |
| 29 | + |
| 30 | + for (const age of ages) { |
| 31 | + ageCount[age]++; |
| 32 | + } |
| 33 | + |
| 34 | + let result = 0; |
| 35 | + for (let ageX = 1; ageX <= 120; ageX++) { |
| 36 | + if (ageCount[ageX] === 0) continue; |
| 37 | + for (let ageY = 1; ageY <= 120; ageY++) { |
| 38 | + if (ageCount[ageY] === 0) continue; |
| 39 | + if (ageY <= 0.5 * ageX + 7) continue; |
| 40 | + if (ageY > ageX) continue; |
| 41 | + if (ageY > 100 && ageX < 100) continue; |
| 42 | + if (ageX === ageY) { |
| 43 | + result += ageCount[ageX] * (ageCount[ageY] - 1); |
| 44 | + } else { |
| 45 | + result += ageCount[ageX] * ageCount[ageY]; |
| 46 | + } |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return result; |
| 51 | +}; |
0 commit comments