Largest Manhattan Distance of Aligned Subsequences
Arrays & HashingAuto-graded · 22 test casesLast updated
Tests identifying that all-nonnegative distance terms let you reduce the search to complete diagonal overlaps, requiring quadratic iteration and overflow awareness.
Problem Statement
You are given two integer arrays arr_a and arr_b. Your task is to select one contiguous subsequence from each array such that both subsequences have identical length, then compute the Manhattan distance (L1 norm) between them. Return the maximum such distance achievable.
The Manhattan distance between subsequence arr_a[i..i+len-1] and subsequence arr_b[j..j+len-1] is calculated as:
sum of |arr_a[i+t] - arr_b[j+t]| for t = 0 to len-1
Both subsequences must be nonempty (length at least 1). The result may require 64-bit integer storage.
Constraints
1 <= len(arr_a), len(arr_b) <= 2500-10^9 <= arr_a[i], arr_b[j] <= 10^9
Notes
- A contiguous subsequence means consecutive elements with no gaps
- The two subsequences can start at any valid positions in their respective arrays
- The length of both subsequences must match, but can be any value from 1 up to the minimum of the two array lengths
Examples
Example 1
Input: largest_manhattan_distance([1, 5, 2], [9, 1, 8])
Output: 18
Example 2
Input: largest_manhattan_distance([10, -5], [2, 8, -5])
Output: 21
Hints
Hint 1
Consider that every absolute difference contributes a non-negative value to the total distance. What does this tell you about extending vs shortening a segment?
Hint 2
Think about all possible alignments between the two arrays. If you visualize a grid where cell (p,q) represents pairing arr_a[p] with arr_b[q], what pattern do equal-length subsequences form?
Hint 3
Each diagonal in the alignment grid corresponds to a fixed offset between starting positions. Since all terms are non-negative, the best choice on any diagonal is the entire diagonal itself.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is recognizing that we can model all possible alignments as diagonals in a conceptual grid where position (p, q) represents pairing arr_a[p] with arr_b[q].
When we choose subsequences of length len starting at positions i in arr_a and j in arr_b, we pair elements with the same relative offset. This means all pairs share a constant offset value d = i - j. Each such alignment corresponds to one diagonal in our grid.
The crucial observation: since absolute differences are always non-negative, extending a segment along a diagonal can never decrease the total distance. Therefore, the optimal choice on any diagonal is to include the entire diagonal—the full overlapping region between the two arrays at that offset.
This reduces our search space from all possible (i, j, len) combinations to just len_a + len_b - 1 diagonals:
-
Diagonals where
arr_astarts at positionstart_a(forstart_a = 0tolen_a - 1) andarr_bstarts at position 0. Each has lengthmin(len_a - start_a, len_b). -
Diagonals where
arr_astarts at position 0 andarr_bstarts at positionstart_b(forstart_b = 1tolen_b - 1). Each has lengthmin(len_a, len_b - start_b).
We compute the sum for each complete diagonal and return the maximum.
Why It Works
- Completeness: Every valid alignment
(i, j, len)lies on exactly one diagonal - Optimality: On any diagonal, the full segment dominates all sub-segments because dropping any element only removes a non-negative contribution
- Correctness: Each full diagonal is itself a valid choice with
len >= 1
Complexity
- Time: O(len_a × len_b). Each grid cell is visited exactly once across all diagonals. With the constraint limits, this is approximately 6.25 million operations.
- Space: O(1) auxiliary space beyond the input arrays.
Overflow Considerations
The maximum possible distance occurs when we have 2500 pairs each contributing up to 2 × 10^9, yielding 5 × 10^12. This exceeds 32-bit signed integer range (approximately 2.1 × 10^9). Python handles arbitrary-precision integers automatically, but languages like C++ or Java require 64-bit types (long long or long).
Solution Code
from typing import List
def largest_manhattan_distance(arr_a: List[int], arr_b: List[int]) -> int:
len_a, len_b = len(arr_a), len(arr_b)
max_distance = 0
# Process diagonals starting from each position in arr_a paired with arr_b[0]
for start_in_a in range(len_a):
distance = 0
overlap_length = min(len_a - start_in_a, len_b)
for step in range(overlap_length):
distance += abs(arr_a[start_in_a + step] - arr_b[step])
max_distance = max(max_distance, distance)
# Process diagonals starting from arr_a[0] paired with each position in arr_b
# (skip arr_b[0] to avoid recounting the diagonal already processed above)
for start_in_b in range(1, len_b):
distance = 0
overlap_length = min(len_a, len_b - start_in_b)
for step in range(overlap_length):
distance += abs(arr_a[step] - arr_b[start_in_b + step])
max_distance = max(max_distance, distance)
return max_distance