Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum distance between a pair of values in Python
Given two arrays nums1 and nums2, we need to find the maximum distance between valid index pairs (i, j). A pair is valid if i <= j and nums1[i] <= nums2[j]. The distance is calculated as (j - i).
For example, with nums1 = [60,40,15,10,5] and nums2 = [115,30,25,15,10], the valid pairs are (0,0), (2,2), (2,3), (3,3), (3,4) and (4,4). The maximum distance is 1 for pairs (2,3) or (3,4).
Algorithm
To solve this efficiently, we follow these steps:
If the last element of
nums1is greater than the first element ofnums2, return 0 (no valid pairs possible)Initialize
i = 0,j = 0, andmax_dist = 0-
While
i < len(nums1):If
j < len(nums2)andnums1[i] <= nums2[j], updatemax_distand incrementjOtherwise, increment both
iandj
Implementation
def solve(nums1, nums2):
# Early termination: if last of nums1 > first of nums2, no valid pairs
if nums1[-1] > nums2[0]:
return 0
i = j = max_dist = 0
while i < len(nums1):
if j < len(nums2) and nums1[i] <= nums2[j]:
max_dist = max(max_dist, j - i)
j += 1
else:
j += 1
i += 1
return max_dist
# Test with example
nums1 = [60, 40, 15, 10, 5]
nums2 = [115, 30, 25, 15, 10]
print(solve(nums1, nums2))
1
How It Works
The algorithm uses a two-pointer approach. When we find a valid pair (i, j) where nums1[i] <= nums2[j], we calculate the distance and move to the next element in nums2. If the pair is invalid, we advance both pointers to find the next potential match.
Example Walkthrough
def solve_with_trace(nums1, nums2):
if nums1[-1] > nums2[0]:
return 0
i = j = max_dist = 0
print(f"nums1: {nums1}")
print(f"nums2: {nums2}")
print("Valid pairs and distances:")
while i < len(nums1):
if j < len(nums2) and nums1[i] <= nums2[j]:
distance = j - i
print(f" Pair ({i},{j}): {nums1[i]} <= {nums2[j]}, distance = {distance}")
max_dist = max(max_dist, distance)
j += 1
else:
j += 1
i += 1
return max_dist
nums1 = [60, 40, 15, 10, 5]
nums2 = [115, 30, 25, 15, 10]
result = solve_with_trace(nums1, nums2)
print(f"Maximum distance: {result}")
nums1: [60, 40, 15, 10, 5] nums2: [115, 30, 25, 15, 10] Valid pairs and distances: Pair (0,0): 60 <= 115, distance = 0 Pair (2,2): 15 <= 25, distance = 0 Pair (2,3): 15 <= 15, distance = 1 Pair (3,3): 10 <= 15, distance = 0 Pair (3,4): 10 <= 10, distance = 1 Pair (4,4): 5 <= 10, distance = 0 Maximum distance: 1
Conclusion
This two-pointer approach efficiently finds the maximum distance between valid pairs in O(m + n) time complexity. The key insight is that we only need to check valid pairs where the first array's element is less than or equal to the second array's element.
