1
# Runtime: 936 ms (Top 28.73%) | Memory: 14.9 MB (Top 52.36%)5
we can try solving this problem by finding the valid age group for each age6
sort the array in descending order7
iterate from right to left8
for current age, find the valid agegroup to which the current age person will send a request9
we can use binary search for that10
if current age is x, then valid age group to send a request is:11
x*0.5 + 7 < age(y) <= x12
we can find the left limit using binary search15
def binary_search(self, arr, low, high, value):18
mid = (low + high) // 220
return self.binary_search(arr, low, mid - 1, value)22
return self.binary_search(arr, mid + 1, high, value)24
def numFriendRequests(self, ages: List[int]) -> int:27
for i in range(len(ages) - 1, -1, -1):28
if i + 1 < len(ages) and ages[i] == ages[i + 1]:29
total_count += prev_count33
lower_limit = 0.5 * ages[i] + 734
index = self.binary_search(ages, 0, i - 1, lower_limit)35
prev_count = i - (index + 1)36
total_count += prev_count