All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0801_0900.s0825_friends_of_appropriate_ages.Solution Maven / Gradle / Ivy

There is a newer version: 1.38
Show newest version
package g0801_0900.s0825_friends_of_appropriate_ages;

// #Medium #Array #Sorting #Binary_Search #Two_Pointers
// #2022_03_23_Time_3_ms_(87.71%)_Space_57.5_MB_(36.15%)

/**
 * 825 - Friends Of Appropriate Ages\.
 *
 * Medium
 *
 * There are `n` persons on a social media website. You are given an integer array `ages` where `ages[i]` is the age of the ith person.
 *
 * A Person `x` will not send a friend request to a person `y` (`x != y`) if any of the following conditions is true:
 *
 * *   `age[y] <= 0.5 * age[x] + 7`
 * *   `age[y] > age[x]`
 * *   `age[y] > 100 && age[x] < 100`
 *
 * Otherwise, `x` will send a friend request to `y`.
 *
 * Note that if `x` sends a request to `y`, `y` will not necessarily send a request to `x`. Also, a person will not send a friend request to themself.
 *
 * Return _the total number of friend requests made_.
 *
 * **Example 1:**
 *
 * **Input:** ages = [16,16]
 *
 * **Output:** 2
 *
 * **Explanation:** 2 people friend request each other.
 *
 * **Example 2:**
 *
 * **Input:** ages = [16,17,18]
 *
 * **Output:** 2
 *
 * **Explanation:** Friend requests are made 17 -> 16, 18 -> 17.
 *
 * **Example 3:**
 *
 * **Input:** ages = [20,30,100,110,120]
 *
 * **Output:** 3
 *
 * **Explanation:** Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.
 *
 * **Constraints:**
 *
 * *   `n == ages.length`
 * *   1 <= n <= 2 * 104
 * *   `1 <= ages[i] <= 120`
**/
public class Solution {
    public int numFriendRequests(int[] ages) {
        int[] counter = new int[121];
        for (int k : ages) {
            counter[k]++;
        }

        int result = 0;
        for (int k = 15; k < counter.length; k++) {
            if (counter[k] == 0) {
                continue;
            }
            result += counter[k] * (counter[k] - 1);

            for (int y = k - 1; y > k / 2.0 + 7; y--) {
                result += counter[k] * counter[y];
            }
        }
        return result;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy