That will never execute under 1 second. There are many things,
1) User input is request, which will be more than seconds in itself.
2) The size is unknown, array manipulation will take a long time.
3) Two loops, even if we improve one, what about second?
4) Math library functions also require some CPU time.
Just one solution, make sure the size of arrays and loops is less than 10 elements. Only then it might work. What I worked,
package hellojava;
public class HelloJava {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = 10;
int a[] = new int[n];
int b[] = new int[n];
for(int i=0;i<n;i++)
{
a[i] = arr[i];
b[i] = arr[i];
}
long sum=0;
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
sum += Math.abs(a[i]-a[j])*(Math.max(b[i],b[j]));
}
}
System.out.println(sum);
}
}
This program, takes exactly 1 second to execute.
run:
1320
BUILD SUCCESSFUL (total time: 1 second)
See? Just what I said. :)