---
# System prepended metadata

title: 0825. Friends Of Appropriate Ages
tags: [Leetcode, FaceBook, Bucket Sort, Prefix Sum, Medium]

---

# 0825. Friends Of Appropriate Ages
###### tags: `Leetcode` `Medium` `FaceBook` `Prefix Sum` `Bucket Sort`
Link: https://leetcode.com/problems/friends-of-appropriate-ages/
## 思路
数学题
先统计每个年龄出现的次数
然后对于每个年龄，他的friends的年龄范围是 (0.5*A+7, A]
所以A的范围就是15到120
对于每一个年龄 i 用prefix sum计算有多少人落在这个区间范围内
那么ans += (cnt[i]-cnt[i-1])*(cnt[i]-cnt[(int)(0.5*i+7)]-1)
-1是因为要排除自己
## Code
```java=
class Solution {
    public int numFriendRequests(int[] ages) {
        // agex >= agey> 0.5*agex+7
        int[] count = new int[121];
        for(int i = 0;i < ages.length;i++){
            count[ages[i]]++;
        }
        for(int i = 1;i < count.length;i++){
            count[i] += count[i-1];
        }
        int res = 0;
        for(int i = 120;i >= 0;i--){
            int smaller = (int)(0.5*i)+7;
            if(smaller<i){
                res += (count[i]-count[i-1])*(count[i]-count[smaller]-1);
            }
        }
        return res;
    }
}
```
