KatInterview

Largest Manhattan Distance of Aligned Subsequences

Arrays & HashingAuto-graded · 22 test cases
MediumAuto-gradedArrays & Hashingarraystwo-pointersmath

Last 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.