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 modulo109 + 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 <= 105
1 <= nums[i] <= 105
Solutions
Solution 1: Prefix Sum of Value Range + Optimized Enumeration
First, we count the occurrences of each element in the array \(nums\) and record them in the array \(cnt\). Then, we calculate the prefix sum of the array \(cnt\) and record it in the array \(s\), i.e., \(s[i]\) represents the count of elements less than or equal to \(i\).
Next, we enumerate the denominator \(y\) and the quotient \(d\). Using the prefix sum array, we can calculate the count of the numerator \(s[\min(mx, d \times y + y - 1)] - s[d \times y - 1]\), where \(mx\) represents the maximum value in the array \(nums\). Then, we multiply the count of the numerator by the count of the denominator \(cnt[y]\), and then multiply by the quotient \(d\). This gives us the value of all fractions that meet the conditions. By summing these values, we can get the answer.
The time complexity is \(O(M \times \log M)\), and the space complexity is \(O(M)\). Here, \(M\) is the maximum value in the array \(nums\).