825. Friends of Appropriate Ages
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.Last updated
Was this helpful?
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.Last updated
Was this helpful?
Was this helpful?
Input:
[20,30,100,110,120]
Output:
Explanation:
Friend requests are made 110 -> 100, 120 -> 110, 120 -> 100.class Solution {
public:
int numFriendRequests(vector<int>& ages) {
int a[121] = {}, res = 0;
for (auto age : ages) a[age]++;
for (auto A = 15; A <= 120; A++)
for(int B = 0.5 * A + 8; B <= A; B++){
res += a[B] * (a[A] - (A == B));
}
return res;
}
};class Solution {
public:
int numFriendRequests(vector<int>& ages) {
int a[121] ={}, res = 0;
for (auto age : ages) a[age]++;
for (int A = 15, lower = 15, acc = 0; A <= 120; acc += a[A], res+= a[A++] * (acc - 1))
// meet the first constraint by removing out those low ages that does not qualify
while(lower <= 0.5 * A + 7) acc -= a[lower++];
return res;
}
};