Блог пользователя nik1996

Автор nik1996, 5 лет назад, По-английски

Hello all, Recently I was attempting the following problem: Given an array of integers, arr. Find sum of floor of (arr[i]/arr[j]) for all pairs of indices (i,j).

e.g. arr[]={1,2,3,4,5}, Sum=27.

I could only think of naive O(n^2) solution. Is there any other better approach?

Thanks in advance.

  • Проголосовать: нравится
  • +10
  • Проголосовать: не нравится

»
5 лет назад, # |
  Проголосовать: нравится +5 Проголосовать: не нравится

Is there any constraint on the values that the elements of the array may have ?

  • »
    »
    5 лет назад, # ^ |
      Проголосовать: нравится 0 Проголосовать: не нравится

    Okay, the size of array n is 1<=n<=1e5 and each element arr[i] is 1<=arr[i]<=1e5.

    • »
      »
      »
      5 лет назад, # ^ |
        Проголосовать: нравится +3 Проголосовать: не нравится

      Firstly, precalculate b[i] values which is equal to count of numbers  ≥ i, it can be done in O(MX). Then for each number, go like a sieve and now calculating how answer change is easy since we know the count of elements between this and next multiple.

      • »
        »
        »
        »
        5 лет назад, # ^ |
        Rev. 3   Проголосовать: нравится +9 Проголосовать: не нравится
        Code with a little comment

        Note: I assume there are no same elements in the array. Otherwise, the code can easily be modified.

        • »
          »
          »
          »
          »
          5 лет назад, # ^ |
            Проголосовать: нравится 0 Проголосовать: не нравится

          You're using suffix sums. I think use of prefix sums would have been more intuitive. But anyways, good logic.

        • »
          »
          »
          »
          »
          5 лет назад, # ^ |
            Проголосовать: нравится 0 Проголосовать: не нравится

          I think this solution is wrong because if the array is [1,2,3,4,5] then the output should be 22 but the output of your code is 27.

          • »
            »
            »
            »
            »
            »
            5 лет назад, # ^ |
              Проголосовать: нравится +1 Проголосовать: не нравится

            The correct output is $$$27$$$. Perhaps you are not considering the case where $$$i = j$$$?

»
5 лет назад, # |
Rev. 2   Проголосовать: нравится +19 Проголосовать: не нравится

You can use another approach. 1. Sort elements. 2. For elements less than sqrt(n) you can run through the array each time(Not forget to remember result of each run, because elements may be repeated). 3. For elements greater than sqrt(n), let's say x, you may use binary search to find the number of elements between xi and x(i+1) (say res), and add res*i to the answer. So overall time complexity will be no less than linearithmic and no greater than O(n*sqrt(n)*log(n)).

»
4 года назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится