There are N
particles present on the X
axis, where, each particle has two properties associated with it, i.e. the Position of the particle and its Attraction-Value
The Attraction-Force between two particles i
and j
is defined as :
Attraction-Force(i,j) = Distance(i,j) × MAX(Attraction_Value[i],Attraction_Value[j])
Since all of them are in a straight line, distance between any 2 particles is equal to the absolute difference between their positions.
You are supposed to calculate the following :
∑N−1i=1∑Nj=i+1(Attraction−Force(i,j))
means
Summation(i,N-1)Summation(j=i+1,N) of (Attraction Of Force(i,j))
Constraints:
1≤N≤2×10^5
1≤Attraction−Value≤10^4
1≤Position≤10^4
Sample Input:
3
1 2
2 4
3 6
Sample Output:
22
I tried in O(n^2)
as following
import java.util.*;
class TestClass {
public static void main(String args[] ) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int a[]=new int[n];
int b[]=new int[n];
for(int i=0;i<n;i++)
{
a[i]=sc.nextInt();
b[i]=sc.nextInt();
}
long sol=0;
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
sol +=Math.abs(a[i]-a[j])*(Math.max(b[i],b[j]));
}
}
System.out.println(sol);
}
}
Please let me know if there are any other optimized way to solve this problem.
Any idea will be appreciated
Thanks in Advance