Problem 1131

Abstract / Summary

Find the largest value obtained by taking the absolute difference between each array element and a chosen integer x.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1131.py

class Solution:
    def maxAbsValExpr(self, arr1: List[int], arr2: List[int]) -> int:
        size = len(arr1) # == len(arr2)

        # minimize / maximize each absolute value each pair arr1/arr2
        diff1 = [  arr1[i] + arr2[i] + i for i in range(size) ]
        result =             max(diff1) - min(diff1)
        diff2 = [  arr1[i] - arr2[i] + i for i in range(size) ]
        result = max(result, max(diff2) - min(diff2))
        diff3 = [ -arr1[i] + arr2[i] + i for i in range(size) ]
        result = max(result, max(diff3) - min(diff3))
        diff4 = [ -arr1[i] - arr2[i] + i for i in range(size) ]
        return   max(result, max(diff4) - min(diff4))
13 lines | 681 bytes | submitted April 2, 2024 | GitHub   18% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 48% (50k+ submissions).

Typical patterns to solve this problem:
  • Array
  • Math
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The maxAbsValExpr method computes the maximum value of the expression

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

for any pair of indices i and j in two equally-sized integer lists. By algebraic transformation the absolute-value expression can be rewritten as the maximum difference among four linear forms, each combining the two arrays and the index. The implementation materialises these four forms, extracts their extrema, and returns the greatest span.

Key Steps

Determining the common length

size = len(arr1)   # == len(arr2)

The method assumes both input lists share the same length and stores that length once, avoiding repeated calls to len.

Building the four transformed arrays

Each transformed array encodes one possible combination of signs for the two input values while always adding the index i. The four comprehensions are:

diff1 = [arr1[i] + arr2[i] + i for i in range(size)]
diff2 = [arr1[i] - arr2[i] + i for i in range(size)]
diff3 = [-arr1[i] + arr2[i] + i for i in range(size)]
diff4 = [-arr1[i] - arr2[i] + i for i in range(size)]
  • diff1 corresponds to the case where both arr1[i] and arr2[i] keep their original sign.
  • diff2 flips the sign of arr2[i].
  • diff3 flips the sign of arr1[i].
  • diff4 flips the sign of both array elements.

Because the index i is added uniformly, the absolute difference of any two indices is captured automatically when the maximum and minimum of a transformed array are compared.

Updating the running result with span calculations

result = max(diff1) - min(diff1)
result = max(result, max(diff2) - min(diff2))
result = max(result, max(diff3) - min(diff3))

For each transformed array the code computes the span (max - min) and keeps the largest span seen so far in the variable result. The use of the built-in max function for the comparison eliminates the need for explicit conditional logic.

Returning the final answer

return max(result, max(diff4) - min(diff4))

The final max call incorporates the span of the fourth transformed array, ensuring that the overall maximum across all four sign configurations is produced.

Edge Cases Handled

When the input lists contain a single element, each transformed array consists of one value; the difference between its maximum and minimum is zero, and the method correctly returns zero, reflecting that no pair of distinct indices exists to contribute a positive distance.

The four separate sign configurations guarantee that any combination of positive or negative values in the original arrays is accommodated. Whether the elements are large, small, or negative, the linear transformations preserve the relative ordering needed for the span calculation, so the method works uniformly across the full integer range.

Because the index i is incorporated directly into each transformed value, the method inherently accounts for the |i - j| component without requiring a separate pass over index differences. This design ensures correct handling of any ordering of indices, including the extreme case where the maximum span occurs between the first and last positions.

Performance Optimizations

The implementation leverages list comprehensions to generate each transformed array in a single pass over the input data, minimizing interpreter overhead. By reusing the result variable for intermediate maxima, the code avoids allocating additional containers for intermediate spans.

The reliance on Python’s highly optimized built-in max and min functions provides fast aggregation of extrema without manual iteration. Finally, the index i is computed once per iteration of the comprehension, so the expression + i does not incur extra lookups or arithmetic outside the comprehension scope. This tight loop structure yields an efficient overall execution profile while maintaining clear, readable logic.

written by openai gpt

ELI5 - Simplified Explanation

Think of these two lists as rows of blocks. To solve the puzzle, the computer looks at two numbers from the lists at the same time along with the spot each number is sitting in. The code creates four different patterns by adding or subtracting these numbers in various ways. By figuring out the biggest and smallest value in each pattern, the computer searches for the biggest gap between the numbers. After looking at all four patterns, it picks the largest gap it found to finish the job. It is like finding the longest distance between any two toys in a big playroom by checking different corners and paths.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 8 | μ = 7.30 | σ = 1.54

Complexity Analysis

Time: linear
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go TS
Progiez C++ Java Python
github black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
JoshCrozier JS
lkwq007 Python
suxrobGM C#
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python, TypeScript
Progiez C++, Java, Python
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
JoshCrozier JavaScript
lkwq007 Python
suxrobGM C#
varunu28 Java
wisdompeak C++
24 links | 13 authors | 7 languages

Videos

5 videos   did my crawler come up with invalid videos ? drop me a line.

Solved On The Same Day

2 medium
3 solutions   April 2, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality