# Friends Of Appropriate Ages in C++

C++Server Side ProgrammingProgramming

Suppose some people will make friend requests. We know their ages, these are stored in ages[i]. So this indicates that the age of the ith person. Now a A will NOT friend request person B (B != A) if any of the following conditions are true −

• age[B] <= 0.5 * age[A] + 7
• age[B] > age[A]
• age[B] > 100 && age[A] < 100

Otherwise, A will friend request B. You can consider that if A requests B, B does not necessarily request A. And also, people will not friend request themselves. So we have to find how many total friend requests are made?

Suppose if the age array is like [16,17,18], then the result will be 2, as the requests will be 17 -> 16, 18 -> 17.

To solve this, we will follow these steps −

• Define an array bucket of size 1000, then store the frequency of ages array elements in the bucket.
• Then find and store the cumulative sum of bucket elements, into bucket
• ret := 0
• for i in range 0 to size of ages array – 1
• x := ages[i], y := (ages[i] / 2) + 7
• if x >= y, then
• ret := bucket[x] – bucket[y]
• if bucket[x] – bucket[y] is non-zero, then decrease ret by 1
• return ret.

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int numFriendRequests(vector<int>& ages) {
vector <int> bucket(1000);
for(int i = 0; i < ages.size(); i++){
bucket[ages[i]]++;
}
for(int i = 1; i < 1000; i++)bucket[i] += bucket[i - 1];
int ret = 0;
for(int i = 0; i < ages.size(); i++){
int x = ages[i];
int y = ((ages[i]) / 2) + 7;
if(x >= y){
ret += (bucket[x] - bucket[y]);
if((bucket[x] - bucket[y]))
ret--;
}
}
return ret;
}
};
main(){
vector<int> v1 = {16, 17, 18};
Solution ob;
cout << (ob.numFriendRequests(v1));
}

## Input

[16,17,18]

## Output

2
Published on 05-May-2020 10:09:41