Leetcode 825. Friends Of Appropriate Ages
Some people will make friend requests. The list of their ages is given and ages[i]
is the age of the i-th person.
Rules for making friends are that age A will not friend request age B if any of the following is true:
age[B] <= 0.5 * age[A] + 7
age[B] > age[A]
age[B] > 100 && age[A] < 100
Otherwise, A
will friend request B
.
Given the list of ages, return the total number of friend requests made.
Input: [16,16]
Output: 2
Explanation: 2 people friend request each other.
Input: [16,17,18]
Output: 2
Explanation: Friend requests are made 17 -> 16, 18 -> 17.
Input: [20,30,100,110,120]
Output: 3
Explanation: Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
1 <= ages.length <= 20000
.1 <= ages[i] <= 120
.ages[i]
where 1 <= ages[i] <= 120
.(ageA, ageB)
using two nested loops. Use the criteria given to check if one can send a friend request to the other.Here is the C++ implementation of the described strategy:
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int numFriendRequests(vector<int>& ages) {
int freq[121] = {0}; // Array to store frequency of ages from 1 to 120
// Count the frequency of each age
for (int age : ages) {
freq[age]++;
}
int totalRequests = 0;
// Check all pairs of possible ages
for (int ageA = 1; ageA <= 120; ageA++) {
for (int ageB = 1; ageB <= 120; ageB++) {
if (freq[ageA] > 0 && freq[ageB] > 0) { // if there are people of ageA and ageB
if (ageB <= 0.5 * ageA + 7 || ageB > ageA || (ageB > 100 && ageA < 100)) {
continue; // B cannot receive a friend request from A
}
if (ageA == ageB) {
totalRequests += freq[ageA] * (freq[ageB] - 1); // A cannot friend request itself
} else {
totalRequests += freq[ageA] * freq[ageB];
}
}
}
}
return totalRequests;
}
};
This solution efficiently counts the valid friend requests according to the given rules.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?