624. Maximum Distance in Arrays

You are given m arrays, where each array is sorted in ascending order.

You can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their absolute difference |a - b|.

Return the maximum distance.

 

Example 1:

Input: arrays = [[1,2,3],[4,5],[1,2,3]]
Output: 4
Explanation: One way to reach the maximum distance 4 is to pick 1 in the first or third array and pick 5 in the second array.

Example 2:

Input: arrays = [[1],[1]]
Output: 0

Example 3:

Input: arrays = [[1],[2]]
Output: 1

Example 4:

Input: arrays = [[1,4],[0,5]]
Output: 4

 

Constraints:

  • m == arrays.length
  • 2 <= m <= 105
  • 1 <= arrays[i].length <= 500
  • -104 <= arrays[i][j] <= 104
  • arrays[i] is sorted in ascending order.
  • There will be at most 105 integers in all the arrays.

Rust Solution

struct Solution;

use std::i32;

impl Solution {
    fn max_distance(arrays: Vec<Vec<i32>>) -> i32 {
        let n = arrays.len();
        let mut min = arrays[0][0];
        let mut max = arrays[0][arrays[0].len() - 1];
        let mut res = 0;
        for i in 1..n {
            let a = &arrays[i];
            let m = a.len();
            res = i32::max(i32::max(max - a[0], a[m - 1] - min), res);
            min = i32::min(a[0], min);
            max = i32::max(a[m - 1], max);
        }
        res
    }
}

#[test]
fn test() {
    let arrays: Vec<Vec<i32>> = vec![vec![1, 2, 3], vec![4, 5], vec![1, 2, 3]];
    assert_eq!(Solution::max_distance(arrays), 4);
}

Having problems with this solution? Click here to submit an issue on github.