1

I have two arrays:

  1. score[n]

  2. pos[n], where n <= 10^5; pos[i],score[i] <= 10^4

Define:

f(i,j) = abs(pos[i]-pos[j])*max(score[i],score[j])

I need to find sum of f(i,j) for all i,js.
I have an algorithm that can solve it in O(n^2) but i want to optimize.
I have spent much time but could not.

Any help is appreciated. Worst case code http://ideone.com/q4qSNh

LaPriWa
  • 1,787
  • 1
  • 12
  • 19
prem
  • 47
  • 2
  • 7

1 Answers1

0

There is a similar question asked earlier. See here.

@Gribouillis has provided a nice algorithm which has O(nlogn) complexity, consisting of sorting and using balanced binary search trees. Look here for the complete answer

Implementation has been left as an exercise.

Community
  • 1
  • 1
User_Targaryen
  • 4,125
  • 4
  • 30
  • 51