LeetCode 825: Friends Of Appropriate Ages
Problem Description
Explanation
To solve this problem, we can iterate through each pair of ages and check if the conditions for sending a friend request are met. We need to keep track of the count of valid friend requests made. We can optimize the process by using a frequency array to store the count of each age, as we only need to consider ages within the given constraints.
- Create a frequency array to store the count of each age in the input array.
- Iterate through each possible pair of ages (x, y) and check if the conditions for sending a friend request are satisfied.
- If the conditions are met, increment the count of friend requests made.
- Return the total count of friend requests made.
Time Complexity: O(n + A), where n is the number of ages and A is the maximum age (120 in this case). Space Complexity: O(A) for the frequency array.
Solutions
class Solution {
public int numFriendRequests(int[] ages) {
int[] freq = new int[121];
for (int age : ages) {
freq[age]++;
}
int count = 0;
for (int i = 0; i <= 120; i++) {
for (int j = 0; j <= 120; j++) {
if (!(j <= 0.5 * i + 7 || j > i || (j > 100 && i < 100))) {
count += freq[i] * freq[j];
if (i == j) {
count -= freq[i];
}
}
}
}
return count;
}
}
Related LeetCode Problems
Loading editor...