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))
Difficulty
and has an acceptance rate of about 48% (50k+ submissions).
Typical patterns to solve this problem:
- Array
- Math
AI Disclaimer
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.
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)]
diff1corresponds to the case where botharr1[i]andarr2[i]keep their original sign.diff2flips the sign ofarr2[i].diff3flips the sign ofarr1[i].diff4flips 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.
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.
Code Quality
Complexity Analysis
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
Other Solutions
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++ |
Videos
Solved On The Same Day
- problem 1105: Filling Bookcase Shelves
- problem 1124: Longest Well-Performing Interval
Extra
- 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