- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find maximum distance between a pair of values in Python
Suppose we have two arrays (non-growing) nums1 and nums2. The index pair (i, j) with 0 <= i < size of nums1, and 0 <= j < size of nums2 is valid if i <= j and nums1 [i] <= nums2 [j] is true. The pair distance is denoted as (j - i). We have to find the maximum distance from each valid pair (i,j). If there are no valid pairs, return 0.
So, if the input is like nums1 = [60,40,15,10,5], nums2 = [115,30,25,15,10], then the output willbe 1 because, here valid pairs are (0,0), (2,2), (2,3), (3,3), (3,4) and (4,4), here maximum distance is 1 for either pair (2,3) or pair (3,4)
To solve this, we will follow these steps −
if last element of nums1 > first eoelement of nums2, then
return 0
i := 0, j := 0 and max_dist := 0
while i < size of nums1, do
if j < size of nums2 and nums1[i] <= nums2[j], then
max_dist := maximum of max_dist and (j-i)
j := j + 1
otherwise,
j := j + 1
i := i + 1
return max_dist
Example
Let us see the following implementation to get better understanding −
def solve(nums1, nums2): if nums1[len(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 nums1 = [60,40,15,10,5] nums2 = [115,30,25,15,10] print(solve(nums1, nums2))
Input
[60,40,15,10,5], [115,30,25,15,10]
Output
1