Similar Problems
Similar Problems not available
Minimum Absolute Sum Difference - Leetcode Solution
Companies:
LeetCode: Minimum Absolute Sum Difference Leetcode Solution
Difficulty: Medium
Topics: sorting binary-search array
Problem statement: Given two arrays of integers, nums1 and nums2, return the minimum absolute sum difference between any two elements from each array.
Solution approach:
-
First, we calculate the sum of absolute differences for each element in nums1 and nums2.
-
We sort nums1 in ascending order.
-
For each element in nums2, we perform a binary search on nums1 to find the closest value to it. We calculate the absolute difference between the two values, subtract it from the previous sum, and store it in a variable.
-
We then update the minimum sum difference if the current sum difference is lower than the previous minimum.
-
Finally, we return the minimum sum difference as the solution.
Code in Python:
class Solution: def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int: mod = 10 ** 9 + 7
# Calculate initial sum of absolute differences
sum_diff = 0
for i in range(len(nums1)):
sum_diff = (sum_diff + abs(nums1[i] - nums2[i])) % mod
# Sort nums1 for binary search
nums1.sort()
# Perform binary search for closest value in nums1 and calculate new sum of absolute differences
min_diff = sum_diff
for i in range(len(nums2)):
closest_val = bisect.bisect_left(nums1, nums2[i])
if closest_val > 0:
new_diff = sum_diff - abs(nums1[closest_val-1] - nums2[i]) + abs(nums1[closest_val] - nums2[i])
min_diff = min(min_diff, new_diff)
# Check if closest value is the first element in nums1
if closest_val == 0:
new_diff = sum_diff - abs(nums1[closest_val] - nums2[i]) + abs(nums1[closest_val+1] - nums2[i])
min_diff = min(min_diff, new_diff)
return min_diff
Minimum Absolute Sum Difference Solution Code
1