Maximum distance between i and j such that i ≤ j and A[i] ≤ B[j]

• Last Updated : 14 Jul, 2021

Given two non-increasing arrays A[] and B[] of size N, the task is to find the maximum distance between i and j such that i ≤ j and A[i] ≤ B[j].

Examples:

Input: A[] = {2, 2, 2}, B[] = {10, 10, 1}
Output: 1
Explanation:
The valid pairs satisfying the conditions are (0, 0), (0, 1), and (1, 1).
Therefore, the maximum distance is 1 between the indices 0 of A[] and 1 of B[].

Input: A[] = {55, 30, 5, 4, 2}, B[] = {100, 20, 10, 10, 5}
Output: 2
Explanation:
The valid pairs satisfying the conditions are (0, 0), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4), and (4, 4).
Therefore, the maximum distance is 2 between the indices 2 of A[] and 4 of B[].

Naive Approach: The simplest approach to solve the problem is to traverse the array A[] and for each element of A[] traverse the array B[] and find the maximum distance between points such that j>=i and B[j] >= A[i].

Time Complexity: O(N2)
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized further by using the binary search algorithm. Follow the steps below to solve the problem:

• Initialize a variable, say ans as 0 to store the maximum distance between two elements in two non-increasing arrays.
• Iterate in the range [0, N-1] using the variable i, and perform the following steps:
• Initialize two variables, say low as i, high as N-1.
• Iterate until low is less than or equal to high and do the following:
• Initialize a variable, say mid as low+(high-low)/2.
• If A[i] is less than equal to B[mid], then update ans to max of ans and mid-i and low to mid+1.
• Otherwise, update high to mid-1.
• Finally, after completing the above steps, print the value of ans as the answer

Below is the implementation of the above approach:

C++

 // C++ program for the above approach #include using namespace std; // Function to find the maximum distance// between two elements satisfying the// conditionsint maxDistance(int A[], int B[], int N){    // Stores the result    int ans = 0;     // Traverse the array    for (int i = 0; i < N; i++) {         int low = i, high = N - 1;         // Iterate until low is less than        // or equal to high        while (low <= high) {             int mid = low + (high - low) / 2;             // If A[i] less than equal to B[mid]            if (A[i] <= B[mid]) {                 // Update answer and low                ans = max(ans, mid - i);                low = mid + 1;            }            // Otherwise            else {                // Update high                high = mid - 1;            }        }    }     // Finally, print the ans    return ans;} // Driver Codeint main(){    // Given Input    int A[] = { 2, 2, 2 };    int B[] = { 10, 10, 1 };    int N = 3;     // Function Call    cout << maxDistance(A, B, N);}

Java

 // Java program for the above approachpublic class GFG {     // Function to find the maximum distance    // between two elements satisfying the    // conditions    static int maxDistance(int A[], int B[], int N)    {               // Stores the result        int ans = 0;         // Traverse the array        for (int i = 0; i < N; i++) {             int low = i, high = N - 1;             // Iterate until low is less than            // or equal to high            while (low <= high) {                 int mid = low + (high - low) / 2;                 // If A[i] less than equal to B[mid]                if (A[i] <= B[mid]) {                     // Update answer and low                    ans = Math.max(ans, mid - i);                    low = mid + 1;                }                // Otherwise                else {                    // Update high                    high = mid - 1;                }            }        }         // Finally, print the ans        return ans;    }     // Driver code    public static void main(String[] args)    {        // Given Input        int A[] = { 2, 2, 2 };        int B[] = { 10, 10, 1 };        int N = 3;         // Function Call        System.out.println(maxDistance(A, B, N));    }} // This code is contributed by abhinavjain194

Python3

 # Python3 program for the above approach # Function to find the maximum distance# between two elements satisfying the# conditionsdef maxDistance(A, B, N):         # Stores the result    ans = 0     # Traverse the array    for i in range(N):        low = i        high = N - 1         # Iterate until low is less than        # or equal to high        while (low <= high):            mid = low + (high - low) // 2             # If A[i] less than equal to B[mid]            if (A[i] <= B[mid]):                 # Update answer and low                ans = max(ans, mid - i)                low = mid + 1             # Otherwise            else:                                 # Update high                high = mid - 1     # Finally, print the ans    return ans # Driver Codeif __name__ == '__main__':         # Given Input    A = [ 2, 2, 2 ]    B = [ 10, 10, 1 ]    N = 3     # Function Call    print(maxDistance(A, B, N))     # This code is contributed by bgangwar59

C#

 // C# program for the above approachusing System;using System.Collections.Generic; public class GFG{    // Function to find the maximum distance    // between two elements satisfying the    // conditions    static int maxDistance(int[] A, int[] B, int N)    {               // Stores the result        int ans = 0;         // Traverse the array        for (int i = 0; i < N; i++) {             int low = i, high = N - 1;             // Iterate until low is less than            // or equal to high            while (low <= high) {                 int mid = low + (high - low) / 2;                 // If A[i] less than equal to B[mid]                if (A[i] <= B[mid]) {                     // Update answer and low                    ans = Math.Max(ans, mid - i);                    low = mid + 1;                }                // Otherwise                else {                    // Update high                    high = mid - 1;                }            }        }         // Finally, print the ans        return ans;    }     // Driver code    public static void Main()    {        // Given Input        int[] A = { 2, 2, 2 };        int[] B = { 10, 10, 1 };        int N = 3;         // Function Call        Console.Write(maxDistance(A, B, N));    }} // This code is contributed by shubhamsingh10

Javascript


Output
1

Time Complexity: O(N×log(N))
Auxiliary Space: O(1)

Efficient Approach: The above approach can be optimized further by using two pointers technique. Follow the steps below to solve the problem:

• Initialize two variables, say, i, and j to perform a two-pointer.
• Iterate until i and j are less than N and perform the following steps:
• If A[i] is greater than B[j], then increment i by 1, because the arrays are sorted in non-increasing.
• Otherwise, update ans to max of ans and j-i, and increment j by 1.
• Finally, after completing the above steps, print the value of ans as the answer.

Below is the implementation of the above approach:

C++

 // C++ program for the above approach #include using namespace std; // Function to find the maximum distance// between two elements in two non increasing// arrays int maxDistance(int A[], int B[], int N){     int i = 0, j = 0;    // Stores the result    int ans = 0;     // Iterate while i and j are less than N    while (i < N && j < N) {         // If A[i] is greater than B[j]        if (A[i] > B[j]) {            ++i;        }        // Otherwise,        else {             // Update the answer            ans = max(ans, j - i);             // Increment j            j++;        }    }     // Finally, print the ans    return ans;} // Driver Codeint main(){    // Given Input    int A[] = { 2, 2, 2 };    int B[] = { 10, 10, 1 };    int N = sizeof(A) / sizeof(A);     // Function Call    cout << maxDistance(A, B, N);}

Java

 // Java program for the above approachimport java.io.*;class GFG {         // Function to find the maximum distance    // between two elements in two non increasing    // arrays       static int maxDistance(int A[], int B[], int N)    {             int i = 0, j = 0;               // Stores the result        int ans = 0;             // Iterate while i and j are less than N        while (i < N && j < N) {                 // If A[i] is greater than B[j]            if (A[i] > B[j]) {                ++i;            }            // Otherwise,            else {                     // Update the answer                ans = Math.max(ans, j - i);                     // Increment j                j++;            }        }             // Finally, print the ans        return ans;    }         // Driver Code    public static void main (String[] args)    {               // Given Input        int A[] = { 2, 2, 2 };        int B[] = { 10, 10, 1 };        int N = A.length;             // Function Call        System.out.println(maxDistance(A, B, N));    }} // This code is contributed by Shubhamsingh10

Python3

 # Python3 program for the above approach # Function to find the maximum distance# between two elements in two non increasing# arraysdef maxDistance(A, B, N):     i = 0    j = 0         # Stores the result    ans = 0     # Iterate while i and j are less than N    while (i < N and j < N):         # If A[i] is greater than B[j]        if (A[i] > B[j]):            i += 1                     # Otherwise,        else:             # Update the answer            ans = max(ans, j - i)             # Increment j            j += 1     # Finally, prthe ans    return ans # Driver Codeif __name__ == '__main__':         # Given Input    A = [ 2, 2, 2 ]    B = [ 10, 10, 1 ]    N = len(A)     # Function Call    print(maxDistance(A, B, N)) # This code is contributed by mohit kumar 29

C#

 // C# program for the above approachusing System;class GFG {         // Function to find the maximum distance    // between two elements in two non increasing    // arrays       static int maxDistance(int []A, int []B, int N)    {             int i = 0, j = 0;               // Stores the result        int ans = 0;             // Iterate while i and j are less than N        while (i < N && j < N) {                 // If A[i] is greater than B[j]            if (A[i] > B[j]) {                ++i;            }            // Otherwise,            else {                     // Update the answer                ans = Math.Max(ans, j - i);                     // Increment j                j++;            }        }             // Finally, print the ans        return ans;    }         // Driver Code    public static void Main (String[] args)    {               // Given Input        int []A = { 2, 2, 2 };        int []B = { 10, 10, 1 };        int N = A.Length;             // Function Call        Console.Write(maxDistance(A, B, N));    }} // This code is contributed by shivanisinghss2110

Javascript


Output
1

Time Complexity: O(N)
Auxiliary Space: O(1)

My Personal Notes arrow_drop_up