Skip to content

1855. Maximum Distance Between a Pair of Values 👍

Approach 1: Sliding Window

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
 public:
  int maxDistance(vector<int>& nums1, vector<int>& nums2) {
    int ans = 0;
    int i = 0;
    int j = 0;

    while (i < nums1.size() && j < nums2.size())
      if (nums1[i] > nums2[j])
        ++i;
      else
        ans = max(ans, j++ - i);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
  public int maxDistance(int[] nums1, int[] nums2) {
    int ans = 0;
    int i = 0;
    int j = 0;

    while (i < nums1.length && j < nums2.length)
      if (nums1[i] > nums2[j])
        ++i;
      else
        ans = Math.max(ans, j++ - i);

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution:
  def maxDistance(self, nums1: list[int], nums2: list[int]) -> int:
    ans = 0
    i = 0
    j = 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

Approach 2: Sliding Window w/o Shrinking

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
 public:
  int maxDistance(vector<int>& nums1, vector<int>& nums2) {
    int i = 0;
    int j = 0;

    for (; i < nums1.size() && j < nums2.size(); ++j)
      if (nums1[i] > nums2[j])
        ++i;

    return i == j ? 0 : j - i - 1;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public int maxDistance(int[] nums1, int[] nums2) {
    int i = 0;
    int j = 0;

    for (; i < nums1.length && j < nums2.length; ++j)
      if (nums1[i] > nums2[j])
        ++i;

    return i == j ? 0 : j - i - 1;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def maxDistance(self, nums1: list[int], nums2: list[int]) -> int:
    i = 0
    j = 0

    while i < len(nums1) and j < len(nums2):
      if nums1[i] > nums2[j]:
        i += 1
      j += 1

    return 0 if i == j else j - i - 1