2
public int minAbsoluteSumDiff(int[] nums1, int[] nums2) {3
int mod = (int) 1e9 + 7;5
// Sorted copy of nums1 to use for binary search6
int[] snums1 = nums1.clone();9
int maxDiff = 0; // maximum difference between original and new absolute diff10
int pos = 0; // where the maximum difference occurs11
int newn1 = 0; // nums1 value to copy to nums1[pos]13
// For each array position i from 0 to n-1, find up to two elements14
// in nums1 that are closest to nums2[i] (one on each side of nums2[i]).15
// Calculate a new absolute difference for each of these elements.16
for (int i = 0; i < nums2.length; i++) {18
int origDiff = Math.abs(nums1[i] - n2);20
// Find the largest element in nums1 that is less than or equal to21
// the current element in nums2, if such an element exists.22
int floor = arrayFloor(snums1, n2);23
if (floor > Integer.MIN_VALUE) {24
// If a valid element exists, calculate a new absolute difference25
// at the current position, and calculate how much smaller this is26
// than the current absolute difference. If the result is better27
// than what we have seen so far, update the maximum difference and28
// save the data for the current position.29
int newDiff = Math.abs(floor - n2);30
int diff = origDiff - newDiff;38
// Find the smallest element in nums1 that is greater than or equal to39
// the current element in nums2, if such an element exists.40
int ceiling = arrayCeiling(snums1, n2);41
if (ceiling < Integer.MAX_VALUE) {43
int newDiff = Math.abs(ceiling - n2);44
int diff = origDiff - newDiff;53
// If we found a replacement value, overwrite the original value.58
// Calculate the absolute sum difference with the replaced value.60
for (int i = 0; i < nums1.length; i++) {61
sum = (sum + Math.abs(nums1[i] - nums2[i])) % mod;68
// Array versions of TreeSet.floor and TreeSet.ceiling71
// Greatest element less than or equal to val72
private int arrayFloor(int[] arr, int val) {74
int hi = arr.length - 1;75
int max = Integer.MIN_VALUE;78
int mid = lo + (hi - lo) / 2;79
if (arr[mid] <= val) {90
// Smallest element greater than or equal to val91
private int arrayCeiling(int[] arr, int val) {93
int hi = arr.length - 1;94
int min = Integer.MAX_VALUE;97
int mid = lo + (hi - lo) / 2;98
if (arr[mid] >= val) {