Problem Description
Given an integer array nums, calculate the sum of floor(nums[i] / nums[j]) for every possible pair (i, j), where floor() returns the integer part of the division. Since the answer may be very large, return it modulo 10^9 + 7.
Key Insights
- Direct double iteration over pairs is too slow for large arrays, so we need to use mathematical observations.
- By computing the frequency of each number and a prefix sum array, we can efficiently count the number of elements within any range.
- For every candidate divisor d that appears in the array, iterate over its multiples. For each multiple, numbers in the range [multiple, multiple + d - 1] will have floor(value/d) equal to the quotient.
- Sum the contributions of pairs by multiplying the frequency of d by the quotient and the count of numbers in the current range.
Space and Time Complexity
Time Complexity: O(max(nums) * log(max(nums))) due to iterating through potential divisors and their multiples. Space Complexity: O(max(nums)) for the frequency and prefix arrays.
Solution
We first calculate the frequency of each number in nums and build a prefix sum array to quickly determine how many numbers fall inside a given range. For each divisor d (from 1 to max(nums)) that appears in the array, iterate over its multiples (j = d, 2d, 3d, ...). For each multiple, the numbers in the interval [j, min(j+d-1, maxValue)] all have floor(x/d) equal to j/d. Multiply frequency[d] by (j/d) and by the count of numbers in that range (obtained from the prefix sums). Sum all such contributions and return the result modulo 10^9+7.