Maximize a sum of absolute differences over index pairs of two arrays

Quick Overview

Given two integer arrays of equal length, find the largest value of |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| over all index pairs. It tests reasoning about absolute values and reducing an all-pairs search to a few linear scans.

Maximize a sum of absolute differences over index pairs of two arrays

Company: Zapier

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: medium

Interview Round: Other

You are given two integer arrays `arr1` and `arr2` of the same length `n`. Return the maximum value of the expression `|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|` taken over all index pairs with `0 <= i, j < n`. ### Function Signature ```python def max_abs_val_expr(arr1: list[int], arr2: list[int]) -> int: ``` ### Constraints - `2 <= len(arr1) == len(arr2) <= 40000` - `-10^6 <= arr1[i], arr2[i] <= 10^6` ### Examples ```text Input: arr1 = [1,2,3,4], arr2 = [-1,4,5,6] Output: 13 ``` The pair `i = 0`, `j = 3` gives `|1 - 4| + |-1 - 6| + |0 - 3| = 3 + 7 + 3 = 13`, and no other pair reaches more. ```text Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4] Output: 20 ``` The pair `i = 4`, `j = 2` gives `|10 - (-5)| + |-4 - (-1)| + |4 - 2| = 15 + 3 + 2 = 20`. ```text Input: arr1 = [1,1], arr2 = [1,1] Output: 1 ``` Both arrays are constant, so only the `|i - j|` term contributes, and it is 1 for the pair `i = 0`, `j = 1`.

Overview: Given two integer arrays of equal length, find the largest value of |arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j| over all index pairs. It tests reasoning about absolute values and reducing an all-pairs search to a few linear scans.

Zapier logo
Zapier
Nov 24, 2026
mediumSoftware EngineerOtherCoding & Algorithms
0
0

You are given two integer arrays arr1 and arr2 of the same length n. Return the maximum value of the expression

|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|

taken over all index pairs with 0 <= i, j < n.

Function Signature

def max_abs_val_expr(arr1: list[int], arr2: list[int]) -> int:

Constraints

  • 2 <= len(arr1) == len(arr2) <= 40000
  • -10^6 <= arr1[i], arr2[i] <= 10^6

Examples

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

The pair i = 0, j = 3 gives |1 - 4| + |-1 - 6| + |0 - 3| = 3 + 7 + 3 = 13, and no other pair reaches more.

Input: arr1 = [1,-2,-5,0,10], arr2 = [0,-2,-1,-7,-4]
Output: 20

The pair i = 4, j = 2 gives |10 - (-5)| + |-4 - (-1)| + |4 - 2| = 15 + 3 + 2 = 20.

Input: arr1 = [1,1], arr2 = [1,1]
Output: 1

Both arrays are constant, so only the |i - j| term contributes, and it is 1 for the pair i = 0, j = 1.