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.

  1. Create a frequency array to store the count of each age in the input array.
  2. Iterate through each possible pair of ages (x, y) and check if the conditions for sending a friend request are satisfied.
  3. If the conditions are met, increment the count of friend requests made.
  4. 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;
    }
}

Loading editor...