#624
Medium Algorithms Maximum distance in arrays
Array Greedy
45.6% acceptance
Feb 20, 2026
1507
122
Given m sorted arrays, find the maximum distance |a - b| where a and b
are from two different arrays.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn max_distance(arrays: Vec<Vec<i32>>) -> i32 {
let mut res = 0;
let mut global_min = arrays[0][0];
let mut global_max = *arrays[0].last().unwrap();
for arr in arrays.iter().skip(1) {
let cur_min = arr[0];
let cur_max = *arr.last().unwrap();
res = res.max((cur_max - global_min).abs());
res = res.max((global_max - cur_min).abs());
global_min = global_min.min(cur_min);
global_max = global_max.max(cur_max);
}
res
}
}