Given an array arr of n integers, find the maximum value of the expression |arr[i] - arr[j]| + |i - j|, where 0 <= i, j < n.
Here, |x| denotes the absolute value of x.
Function Signature
def max_abs_diff_plus_distance(arr: list[int]) -> int:
Rules
-
Indices are 0-based.
i
and
j
range independently over all positions, so
i = j
is allowed (it contributes 0), and swapping
i
and
j
gives the same value.
-
Return only the maximum value, not the indices that reach it.
Constraints
-
2 <= len(arr) <= 10^5
-
-10^9 <= arr[i] <= 10^9
Examples
Input: arr = [1,2,3,1]
Output: 4
Choosing i = 2 and j = 0 gives |3 - 1| + |2 - 0| = 2 + 2 = 4. The only pair at distance 3 (indices 0 and 3) has equal values and scores 3, and every other pair scores at most 4.
Input: arr = [-70,-64,-6,-56,64,61,-57,16,48,-98]
Output: 167
The maximum is reached at i = 4 (value 64) and j = 9 (value -98): |64 - (-98)| + |4 - 9| = 162 + 5 = 167.
Input: arr = [4,4]
Output: 1
The two values are equal, so only the index distance counts: |4 - 4| + |0 - 1| = 1.