I have an array of numbers with even size, here is my task:
a) Discard any 2 elements from the array. b) Then pair the elements and calculate the sum of differences between the elements in the pair such that the sum is minimum.
Example:
array size even say 8.
array elements : 1,3,4,6,3,4,100,200
Ans:
5
Explanation:
Here I will remove 100 and 200, as pairing them gives me a difference of (200 - 100) = 100. So remaining elements are [1,3,4,6,3,4] Pairs with minimum sum are : (1 3) , (4 3), (6 4). = |3-1| = 2, |4-3|=1,|6-4| = 2. So Sum = 2 + 1 + 2 = 5
Example:
array size even say 4.
array elements : 1,50,51,60
Ans:
1
Explanation: Here I will remove 1 and 60 so I will get the minimum sum. So the remaining elements are [50, 51], same as the adjacent [50 51] = 1. My code will fail for this case and returns 49.
How to achieve this in java?
I tried sorting the elements like this but this is not the correct approach for all kinds of inputs.
public static int process(int[] a) {
int n = a.length;
int n1 = n/2-1;
Arrays.sort(arr);
int sum = 0;
for(int i=0; i<n1*2; i+=2) {
sum += a[i+1] - a[i];
}
return sum;
}
