Minimum Absolute Sum Difference — LeetCode 1818 Python Solution

MediumArrayBinary SearchOrdered SetSorting
Problem
#1818
Reading time
3 min

The problem

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).

Example

Input
nums1 = [1,7,5], nums2 = [2,3,5]
Output
3
Explanation
There are two possible optimal solutions:

Python solution

Python
class Solution:
    def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:
        mod = 10**9 + 7
        nums = sorted(nums1)
        s = sum(abs(a - b) for a, b in zip(nums1, nums2)) % mod
        mx = 0
        for a, b in zip(nums1, nums2):
            d1, d2 = abs(a - b), inf
            i = bisect_left(nums, b)
            if i < len(nums):
                d2 = min(d2, abs(nums[i] - b))
            if i:
                d2 = min(d2, abs(nums[i - 1] - b))
            mx = max(mx, d1 - d2)
        return (s - mx + mod) % mod

Complexity

MeasureComplexity
TimeO(n \times \log n)
SpaceO(n) auxiliary

Pattern: Monotonic Stack

Answer "what is the next greater element" for every position in one pass. LeetCode 1818. Minimum Absolute Sum Difference is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.

The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1818. Minimum Absolute Sum Difference?
LeetCode 1818. Minimum Absolute Sum Difference is rated Medium on LeetCode.
What is the time complexity of LeetCode 1818. Minimum Absolute Sum Difference?
The Python solution on this page runs in O(n \times \log n).
What is the space complexity of LeetCode 1818. Minimum Absolute Sum Difference?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1818. Minimum Absolute Sum Difference cover?
LeetCode 1818. Minimum Absolute Sum Difference is tagged Array, Binary Search, Ordered Set and Sorting on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview