Skip to main content
Back to problems
#1855
Medium Algorithms

Maximum distance between a pair of values

Array Two Pointers Binary Search
54.3% acceptance
Feb 25, 2026
1264
32
You are given two non-increasing 0-indexed integer arrays nums1 and nums2. A pair of indices (i, j), where 0 <= i < nums1.length and 0 <= j < nums2.length, is valid if both i <= j and nums1[i] <= nums2[j]. The distance of the pair is j - i. Return the maximum distance of any valid pair (i, j). If there are no valid pairs, return 0.

Solution

Rust
Time O(n²)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_distance(nums1: Vec<i32>, nums2: Vec<i32>) -> i32 {
    let n2 = nums2.len();
    let mut ans = 0i32;
    let mut i = 0usize;
    for j in 0..n2 {
      // advance i while nums1[i] > nums2[j]
      while i < nums1.len() && nums1[i] > nums2[j] {
        i += 1;
      }
      if i < nums1.len() && i <= j {
        ans = ans.max(j as i32 - i as i32);
      }
    }
    ans
  }
}