Maximum of Absolute Value Expression — LeetCode 1131 Python Solution

MediumArrayMath
Problem
#1131
Reading time
2 min

The problem

Given two arrays of integers with equal lengths, return the maximum value of: |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| where the maximum is taken over all 0 <= i, j < arr1.length.

Example

Input
arr1 = [1,2,3,4], arr2 = [-1,4,5,6]
Output
13

Python solution

Python
class Solution:
    def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
        dirs = (1, -1, -1, 1, 1)
        ans = -inf
        for a, b in pairwise(dirs):
            mx, mi = -inf, inf
            for i, (x, y) in enumerate(zip(arr1, arr2)):
                mx = max(mx, a * x + b * y + i)
                mi = min(mi, a * x + b * y + i)
                ans = max(ans, mx - mi)
        return ans

Complexity

MeasureComplexity
TimeO(n), where n is the length of the array
SpaceO(1) auxiliary

Pattern: Math and Number Theory

Find the closed form, the invariant, or the modular identity — and skip the loop entirely. LeetCode 1131. Maximum of Absolute Value Expression is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Math.

The math and number theory guide has the Python template for the pattern and the 485 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1131. Maximum of Absolute Value Expression?
LeetCode 1131. Maximum of Absolute Value Expression is rated Medium on LeetCode.
What is the time complexity of LeetCode 1131. Maximum of Absolute Value Expression?
The Python solution on this page runs in O(n), where n is the length of the array.
What is the space complexity of LeetCode 1131. Maximum of Absolute Value Expression?
The Python solution on this page uses O(1) auxiliary space.
What topics does LeetCode 1131. Maximum of Absolute Value Expression cover?
LeetCode 1131. Maximum of Absolute Value Expression is tagged Array and Math 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