// Java implementation for the above approach
import java.util.Arrays;
class GFG {
// Function to find minimum sum absolute
// difference from two arrays
public static int minAbsoluteDiffSum(int a[], int b[], int n)
{
// Variable to store the
// initial absolute difference sum
int sum = 0;
// Make another vector to
// store the elements of a in
// sorted order
int[] nums = new int[n];
for (int i = 0; i < n; i++) {
nums[i] = a[i];
sum += Math.abs(a[i] - b[i]);
}
// Variable to store the minimum sum
int min_answer = sum;
// Sort the copy array of a
Arrays.sort(nums);
for (int i = 0; i < n; i++)
{
// Binary Search for elements
// just greater than b[i].
int it = lower_bound(nums, 0, nums.length, b[i]);
// Take minimum from just
// greater and less than b[i].
int cur = Math.min(Math.abs(nums[(Math.min(it, (n - 1)))] - b[i]),
Math.abs(nums[(Math.max(0, it - 1))] - b[i]));
// update the minimum answer
if (cur < Math.abs(a[i] - b[i])) {
min_answer = Math.min(min_answer, sum - Math.abs(a[i] - b[i]) + cur);
}
}
return min_answer;
}
public static int lower_bound(int[] a, int low, int high, int e) {
if (low < 0)
return 0;
if (low >= high) {
if (e <= a[low])
return low;
return low + 1;
}
int mid = (int)Math.floor((low + high) / 2);
if (e > a[mid])
return lower_bound(a, mid + 1, high, e);
return lower_bound(a, low, mid, e);
}
// Driver Code
public static void main(String args[]) {
int a[] = { 1, 9, 4, 2 };
int b[] = { 2, 3, 7, 1 };
int N = a.length;
System.out.println(minAbsoluteDiffSum(a, b, N));
}
}
// This code is contributed by saurabh_jaiswal.