Skip to content

825. Friends Of Appropriate Ages

https://leetcode.com/problems/friends-of-appropriate-ages/

js
/**
 * @param {number[]} ages
 * @return {number}
 */
var numFriendRequests = function(ages) {
  const numInAge = new Array(121).fill(0)
  for (let age of ages) {
    numInAge[age]++
  }

  const sumInAge = new Array(121).fill(0)
  for (let i = 1; i < 121; i++) {
    sumInAge[i] = numInAge[i] + sumInAge[i - 1]
  }

  let res = 0
  for (let i = 15; i < 121; i++) {
    if (numInAge[i] === 0) {
      continue
    }
    const count = sumInAge[i] - sumInAge[(i / 2 >> 0) + 7]
    res += count * numInAge[i] - numInAge[i]
  }

  return res
}
py
class Solution:

    def numFriendRequests(self, ages):
        """
        :type ages: List[int]
        :rtype: int
        """
        num_in_age = [0] * 121
        for age in ages:
            num_in_age[age] += 1

        sum_in_age = [0] * 121
        for i in range(1, 121):
            sum_in_age[i] = num_in_age[i] + sum_in_age[i - 1]

        res = 0
        for i in range(15, 121):
            if num_in_age[i] == 0:
                continue
            count = sum_in_age[i] - sum_in_age[i // 2 + 7]
            res += count * num_in_age[i] - num_in_age[i]

        return res