Maximum Distance Between a Pair of Values

Updated on 16 June, 2025
Maximum Distance Between a Pair of Values header image

Problem Statement

You are provided with two non-increasing integer arrays, nums1 and nums2, both using 0-based indexing. A valid pair of indices (i, j) is defined under two conditions: firstly, the index i from nums1 must not exceed the index j from nums2 (i <= j), and secondly, the value at nums1[i] must be less than or equal to the value at nums2[j] (nums1[i] <= nums2[j]). The distance of such a pair is the difference j - i. Your task is to determine the maximum possible distance for such valid index pairs and return this value. If no valid pairs exist, the function should return 0. Each array element must follow the non-increasing order, which means each subsequent element must be less than or equal to its predecessor.

Examples

Example 1

Input:

nums1 = [55,30,5,4,2], nums2 = [100,20,10,10,5]

Output:

2

Explanation:

The valid pairs are (0,0), (2,2), (2,3), (2,4), (3,3), (3,4), and (4,4).
The maximum distance is 2 with pair (2,4).

Example 2

Input:

nums1 = [2,2,2], nums2 = [10,10,1]

Output:

1

Explanation:

The valid pairs are (0,0), (0,1), and (1,1).
The maximum distance is 1 with pair (0,1).

Example 3

Input:

nums1 = [30,29,19,5], nums2 = [25,25,25,25,25]

Output:

2

Explanation:

The valid pairs are (2,2), (2,3), (2,4), (3,3), and (3,4).
The maximum distance is 2 with pair (2,4).

Constraints

  • 1 <= nums1.length, nums2.length <= 105
  • 1 <= nums1[i], nums2[j] <= 105
  • Both nums1 and nums2 are non-increasing.

Approach and Intuition

Given the constraints and examples, the brute-force approach of comparing all possible pairs (i, j) with i from nums1 and j from nums2 is suboptimal due to potential high computational cost when array lengths are maximized. The following approach can be used for a more efficient solution:

  1. Utilize a two-pointer technique to leverage the sorted (non-increasing) nature of nums1 and nums2.

  2. Set initial pointers at the start of both arrays. Begin with i=0 for nums1 and j=0 for nums2.

    • Increase j until nums1[i] is less than or equal to nums2[j] or j reaches the end. This ensures compliance with the condition nums1[i] <= nums2[j].

    • If a valid j is found for nums1[i], calculate j - i and update the maximum distance if this value exceeds the current known maximum.

    • Move to the next element in nums1 by incrementing i and try to find a new j starting from the current j (since nums2 is non-increasing, a valid j for nums1[i] will be valid for all subsequent i).

    • Repeat this until you have traversed all elements of nums1 while ensuring the above conditions.

  • Return the recorded maximum distance. If no valid pairs were found (if the maximum distance wasn't updated), return 0.

This method works efficiently as each pointer only moves forward through its respective array, ensuring that every element is considered exactly once, achieving optimal performance in respect to time complexity.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int findMaxDistance(vector<int>& array1, vector<int>& array2) {
        int maxDist = 0, index1 = 0, index2 = 0;
        
        while (index1 < array1.size() && index2 < array2.size()) {
            if (array1[index1] > array2[index2]) {
                index1++;
            } else {
                maxDist = max(maxDist, index2 - index1);
                index2++;
            }
        }
        
        return maxDist;
    }
};

This C++ solution addresses the problem of finding the maximum distance between a pair of values from two vectors where the value from the second vector is not smaller than the value from the first. The method findMaxDistance performs this check and determines the maximum permissible distance.

  • The function initializes maxDist, index1, and index2 to zero to keep track of the maximum distance and the current indices in array1 and array2.
  • It employs a while loop to iterate through both arrays as long as neither index exceeds its respective array's length. This ensures all possible pairs of elements are considered.
  • Inside the loop, a condition checks if the current element in array1 is greater than the element in array2 at their respective indices. If true, it increments index1 to check the next element in array1.
  • If the element in array1 is not greater, it calculates the distance between the indices (index2 - index1) and updates maxDist if this new distance is greater than the previously recorded maximum distance. Subsequently, index2 is incremented.
  • After the loop concludes, maxDist holds the required maximum distance, which is then returned.

This approach ensures the solution is optimized and only viable pairs (where array1[index] is not greater than array2[index]) are considered, improving both clarity and efficiency of the algorithm.

java
class Solution {
    public int maximumSeparation(int[] array1, int[] array2) {
        int maxDiff = 0, index1 = 0, index2 = 0;
        while (index1 < array1.length && index2 < array2.length) {
            if (array1[index1] > array2[index2]) {
                index1++;
            } else {
                maxDiff = Math.max(maxDiff, index2 - index1);
                index2++;
            }
        }
        
        return maxDiff;
    }
}

This Java program aims to find the maximum distance between elements from two arrays under specific comparison conditions. The function maximumSeparation accepts two integer arrays, array1 and array2, and uses two pointers, index1 and index2, to traverse these arrays.

  • Initialize maxDiff to track the maximum separation distance.
  • Use a while loop to iterate through both arrays till one of them is fully traversed.
  • Compare elements from array1 and array2:
    • If array1[index1] is greater than array2[index2], increment index1.
    • Otherwise, calculate the difference between the current positions (index2 - index1) to update maxDiff, and increment index2.

The function returns the value of maxDiff, which represents the largest valid index difference for which the value at array1[index1] is not greater than array2[index2]. This approach ensures an efficient O(n+m) complexity where n and m are the lengths of array1 and array2, respectively, by using a linear pass through the arrays without the need for nested loops.

python
class Solution:
    def maximumGap(self, arr1: List[int], arr2: List[int]) -> int:
        max_gap = 0
        idx1, idx2 = 0, 0

        while idx1 < len(arr1) and idx2 < len(arr2):
            if arr1[idx1] > arr2[idx2]:
                idx1 += 1
            else:
                max_gap = max(max_gap, idx2 - idx1)
                idx2 += 1

        return max_gap

The provided Python script defines a method to calculate the maximum gap in terms of indices between two sorted arrays, arr1 and arr2. The arrays must contain integers. The function, maximumGap, iterates through both arrays by using two pointers (idx1 for arr1 and idx2 for arr2) and computes the maximum gap where the value in arr1 is not greater than the value in arr2.

Follow these steps to understand the process implemented:

  1. Initialize max_gap to 0, and pointer indices idx1 and idx2 to 0.
  2. Use a while loop to traverse elements in both arrays until one of the pointers reaches the end of its respective array.
  3. Compare the current elements in arr1 and arr2 using the pointers.
  4. If the element in arr1 is greater, increment idx1.
  5. If the element in arr1 is less than or equal to the element in arr2, update max_gap if the current gap (idx2 - idx1) is larger than the recorded max_gap, then increment idx2.
  6. Continue to loop until the end of one of the arrays.
  7. Return max_gap, which is the maximum distance in indices between corresponding elements in the two arrays that meet the condition (arr1[idx1] <= arr2[idx2]).

This method is efficient with array traversal due to the use of two-pointer technique. Ensure that both arrays are sorted to properly utilize this method.

Comments

No comments yet.