Maximum Distance Between a Pair of Values

medium two pointers array greedy

Problem

You are given two non-increasing integer arrays nums1 and nums2 (each sorted from largest to smallest). A pair of indices (i, j) is valid when i <= j and nums1[i] <= nums2[j]. Its distance is j − i. Return the largest distance over all valid pairs, or 0 if no valid pair exists.

Inputnums1 = [55, 30, 5, 4, 2], nums2 = [100, 20, 10, 10, 5]
Output2
The pair (i=2, j=4) is valid because 2 <= 4 and nums1[2]=5 <= nums2[4]=5, giving distance 4 − 2 = 2, the maximum possible.

def max_distance(nums1, nums2):
    i, j, ans = 0, 0, 0
    while i < len(nums1) and j < len(nums2):
        if nums1[i] > nums2[j]:
            i += 1
        else:
            ans = max(ans, j - i)
            j += 1
    return ans
function maxDistance(nums1, nums2) {
  let i = 0, j = 0, ans = 0;
  while (i < nums1.length && j < nums2.length) {
    if (nums1[i] > nums2[j]) {
      i++;
    } else {
      ans = Math.max(ans, j - i);
      j++;
    }
  }
  return ans;
}
class Solution {
    public int maxDistance(int[] nums1, int[] nums2) {
        int i = 0, j = 0, ans = 0;
        while (i < nums1.length && j < nums2.length) {
            if (nums1[i] > nums2[j]) {
                i++;
            } else {
                ans = Math.max(ans, j - i);
                j++;
            }
        }
        return ans;
    }
}
int maxDistance(vector<int>& nums1, vector<int>& nums2) {
    int i = 0, j = 0, ans = 0;
    while (i < (int)nums1.size() && j < (int)nums2.size()) {
        if (nums1[i] > nums2[j]) {
            i++;
        } else {
            ans = max(ans, j - i);
            j++;
        }
    }
    return ans;
}
Time: O(n + m) Space: O(1)