Rakuten | Online Stage | Sum Of Floored Pairs

I faced this problem in a recent online coding exam for Rakuten. I was unable to optimize it in the given short span of time. Need some help.

You are given an array A of length n. All elements are greater than zero.
Now, you need to calculate the Sum of Floor(A[i] / A[j]) for all pairs, i.e. for 0 <= i, j < n
Return the answer modulo 1000003

Sample:

Input: [3,3,4,4,5]
Output: 17

Input: [1,2,3,4,5]
Output: 27

Explanation (Second Sample Case)

Table denoting the floor division [i.e. floor(A_i / A_j)]

12345
110000
221000
331100
442110
552111

Sum = 27

A simple brute force method would have a quadratic time complexity. What I am looking for is linear (O(n)) or atleast O(n log n)

Any help would be appreciated, thanks.

Comments (5)