[LeetCode] Minimum Absolute Sum Difference

1818. Minimum Absolute Sum Difference

You are given two positive integer arrays nums1 and nums2, both of length n.

The absolute sum difference of arrays nums1 and nums2 is defined as the sum of |nums1[i] - nums2[i]| for each 0 <= i < n (0-indexed).

You can replace at most one element of nums1 with any other element in nums1 to minimize the absolute sum difference.

Return the minimum absolute sum difference after replacing at most one element in the array nums1. Since the answer may be large, return it modulo 109 + 7.

|x| is defined as:

  • x if x >= 0, or
  • -x if x < 0.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int minAbsoluteSumDiff(vector<int>& nums1, vector<int>& nums2) {
int res(0), mod(1e9 + 7), diff(INT_MIN);
vector<int> sortedNums1(begin(nums1), end(nums1));
sort(begin(sortedNums1), end(sortedNums1));
for(int i = 0; i < nums1.size(); i++) {
int absolute = abs(nums1[i] - nums2[i]), change(INT_MAX);
res = (res + absolute) % mod;
auto it = lower_bound(begin(sortedNums1), end(sortedNums1), nums2[i]);
if(it != end(sortedNums1)) {
change = min(change, abs(*it - nums2[i]));
}
if(it != begin(sortedNums1)) {
change = min(change, abs(*(prev(it)) - nums2[i]));
}
diff = max(diff, abs(absolute - change));
}

res -= diff;
return res < 0 ? res + mod : res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/12/14/PS/LeetCode/minimum-absolute-sum-difference/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.