|
| 1 | +// Source : https://leetcode.com/problems/sum-of-floored-pairs/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-05-22 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 |
| 8 | + * <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 10^9 + 7. |
| 9 | + * |
| 10 | + * The floor() function returns the integer part of the division. |
| 11 | + * |
| 12 | + * Example 1: |
| 13 | + * |
| 14 | + * Input: nums = [2,5,9] |
| 15 | + * Output: 10 |
| 16 | + * Explanation: |
| 17 | + * floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0 |
| 18 | + * floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1 |
| 19 | + * floor(5 / 2) = 2 |
| 20 | + * floor(9 / 2) = 4 |
| 21 | + * floor(9 / 5) = 1 |
| 22 | + * We calculate the floor of the division for every pair of indices in the array then sum them up. |
| 23 | + * |
| 24 | + * Example 2: |
| 25 | + * |
| 26 | + * Input: nums = [7,7,7,7,7,7,7] |
| 27 | + * Output: 49 |
| 28 | + * |
| 29 | + * Constraints: |
| 30 | + * |
| 31 | + * 1 <= nums.length <= 10^5 |
| 32 | + * 1 <= nums[i] <= 10^5 |
| 33 | + ******************************************************************************************************/ |
| 34 | + |
| 35 | +class Solution { |
| 36 | +public: |
| 37 | + int sumOfFlooredPairs(vector<int>& nums) { |
| 38 | + const int MAX_NUM = 100001; |
| 39 | + int cnt[MAX_NUM] = {0}; |
| 40 | + int maxn = 0; |
| 41 | + for(auto& n : nums) { |
| 42 | + cnt[n]++; |
| 43 | + maxn = max(maxn, n); |
| 44 | + } |
| 45 | + |
| 46 | + vector<vector<int>> stats; |
| 47 | + for(int i=1; i<MAX_NUM; i++) { |
| 48 | + if (cnt[i] > 0) { |
| 49 | + stats.push_back({i, cnt[i]}); |
| 50 | + } |
| 51 | + cnt[i] += cnt[i-1]; |
| 52 | + } |
| 53 | + |
| 54 | + const int MOD = 1e9+7; |
| 55 | + int result = 0; |
| 56 | + for(int i=0; i < stats.size(); i++) { |
| 57 | + int n = stats[i][0]; |
| 58 | + int c = stats[i][1]; |
| 59 | + |
| 60 | + for(int x=2; x <= maxn/n+1; x++) { |
| 61 | + int pre = (x-1) * n - 1; |
| 62 | + int cur = min( x * n - 1, MAX_NUM-1); |
| 63 | + result = (result + (cnt[cur] - cnt[pre]) * long(x-1) * c) % MOD; |
| 64 | + } |
| 65 | + } |
| 66 | + return result; |
| 67 | + } |
| 68 | +}; |
0 commit comments