LeetCode 1862: Sum of Floored Pairs Solution

Master LeetCode problem 1862 (Sum of Floored Pairs), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1862. Sum of Floored Pairs

Problem Explanation

Explanation:

To solve this problem, we need to iterate through all pairs of indices i and j in the array and calculate floor(nums[i] / nums[j]). We can optimize this process by counting the frequencies of each number in the array and then using these frequencies to calculate the answer efficiently.

  1. Count Frequencies:

    • Count the frequency of each number in the array.
  2. Calculate Contribution of Each Number:

    • For each number x in the array, calculate the contribution of x to the final answer by iterating through multiples of x and adding the frequency of each multiple multiplied by the difference between the upper and lower bounds of the interval (num / x) where num is the maximum number in the array.
  3. Calculate Total Sum:

    • Sum up the contributions of all numbers to get the final answer modulo 10^9 + 7.

:

Solution Code

class Solution {
    public int sumOfFlooredPairs(int[] nums) {
        int MOD = 1000000007;
        int maxNum = 0;
        for (int num : nums) {
            maxNum = Math.max(maxNum, num);
        }
        
        int[] freq = new int[maxNum + 1];
        for (int num : nums) {
            freq[num]++;
        }
        
        long[] prefixSum = new long[maxNum + 1];
        for (int i = 1; i <= maxNum; i++) {
            prefixSum[i] = prefixSum[i - 1] + freq[i];
        }
        
        long result = 0;
        for (int num : nums) {
            for (int j = 1; j * num <= maxNum; j++) {
                int lower = j * num - 1;
                int upper = Math.min((j + 1) * num - 1, maxNum);
                result = (result + (prefixSum[upper] - prefixSum[lower]) * j) % MOD;
            }
        }
        
        return (int) result;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1862 (Sum of Floored Pairs)?

This page provides optimized solutions for LeetCode problem 1862 (Sum of Floored Pairs) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1862 (Sum of Floored Pairs)?

The time complexity for LeetCode 1862 (Sum of Floored Pairs) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1862 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1862 in Java, C++, or Python.

Back to LeetCode Solutions