Array formed using sum of absolute differences of that element with all other elements | Java program for the above approach ; Function to return the new array ; Length of the arraylist ; Initialize the Arraylist ; Sum of absolute differences of element with all elements ; Initialize int sum to 0 ; Add the value of sum to ans ; Return the final ans ; Driver Code ; Given array arr [ ] ; Function Call
import java . util . * ; class GFG { private static List < Integer > calculate ( int [ ] arr ) { int n = arr . length ; List < Integer > ans = new ArrayList < Integer > ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { int sum = 0 ; for ( int j = 0 ; j < arr . length ; j ++ ) { sum += Math . abs ( arr [ i ] - arr [ j ] ) ; } ans . add ( sum ) ; } return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 3 , 5 , 6 } ; System . out . println ( calculate ( arr ) ) ; } }