Sum of Floored Pairs Problem
Description
LeetCode Problem 1862.
Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 10^9 + 7.
The floor() function returns the integer part of the division.
Example 1:
Input: nums = [2,5,9]
Output: 10
Explanation:
floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0
floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1
floor(5 / 2) = 2
floor(9 / 2) = 4
floor(9 / 5) = 1
We calculate the floor of the division for every pair of indices in the array then sum them up.
Example 2:
Input: nums = [7,7,7,7,7,7,7]
Output: 49
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^5
Solution
Approach: Counting With Prefix Sums
Let M be the largest value. Count how often each value occurs in cnt, and build the prefix sums s, so s[v] is the number of elements that are at most v.
Fix the denominator y (only values that occur). The numerators x with floor(x / y) = d are exactly those in [d*y, d*y + y - 1], and there are s[min(M, d*y + y - 1)] - s[d*y - 1] of them. Each contributes d, and the denominator occurs cnt[y] times, so add cnt[y] * d * (that count) for every d with d*y <= M, modulo 10^9 + 7.
For each y there are about M / y values of d, so the total work is a harmonic sum.
Complexity: O(M log M) time and O(M) space.
from collections import Counter
class Solution:
def sumOfFlooredPairs(self, nums: List[int]) -> int:
mod = 10**9 + 7
cnt = Counter(nums)
mx = max(nums)
s = [0] * (mx + 1)
for i in range(1, mx + 1):
s[i] = s[i - 1] + cnt[i]
ans = 0
for y in range(1, mx + 1):
if cnt[y]:
d = 1
while d * y <= mx:
ans += cnt[y] * d * (s[min(mx, d * y + y - 1)] - s[d * y - 1])
ans %= mod
d += 1
return ans