Skip to content
Related Articles

Related Articles

Improve Article

Maximize distance between two elements of Array by at most X swaps

  • Last Updated : 01 Jun, 2021
Geek Week

Given an array arr[] of unique elements and three integers X, A, and B. The task is to print the maximum possible distance between elements A and B in atmost X swaps with the adjacent elements.
Examples: 
 

Input: arr[] = {5, 1, 3, 2}, X = 1, A = 2, B = 3 
Output:
Explanation: 
3 is swapped with it’s adjacent element 1. So, the distance between element 3 and 2 is 2 and no more interchanges are possible since X = 1.
Input: arr = {100, 33, 10, 1}, X = 5, A = 100, B = 1 
Output:
Explanation: 
As the elements are already the beginning and ending element, the distance between them is already maximized. 
 

Approach: The following steps can be followed to compute the result: 
 

  • In case the given X is 0, then |index(A)-index(B)| is returned as final answer.
  • If the elements are already at index 0 and n-1, return N-1 as the distance is already maximized.
  • Else, the greater index element is swapped X times with their adjacent element till it is less than the size of the array.
  • After reaching the end of the array if X > 0; then the smaller index element is swapped with its previous elements till X is not equal to 0.

Below is the implementation of the above approach:
 

C++




// C++ program for the above approach
 
#include <iostream>
using namespace std;
 
// Function to maximize the distance
// between the two elements of the
// array by at most X swaps
void max_distance(int a[], int n, int x,
                  int A, int B)
{
    // Initialize the variables
    int g = 0, h = 0;
 
    // Iterate till the length of the array
    for (int i = 0; i < n; i++) {
        // Check if current element is A
        if (a[i] == A)
            // Store index
            g = i;
 
        // Check if current element is B
        if (a[i] == B)
            // Store index
            h = i;
    }
 
    // If X = 0, swapping can not be done
    if (x == 0) {
        cout << abs(g - h);
    }
 
    // If elements are at starting and ending
    // indices, then the distance
    // is already maximum
    else if ((g == 0) && (h == (n - 1)))
        cout << n - 1 << endl;
 
    else if ((g == n - 1) && (h == 0))
        cout << n - 1 << endl;
 
    else {
 
        // Greater index is incremented
        // till x > 0 and the
        // index of element < size of array
        if (h > g) {
            while ((x > 0) && (h < n - 1)) {
                h++;
                x--;
            }
 
            // Check if reached the size of array
            // and x > 0, then the
            // smaller index is decremented
            if (x > 0) {
                while ((x > 0) && (g > 0)) {
                    g--;
                    x--;
                }
            }
            cout << h - g << endl;
        }
 
        // Greater index is incremented till x>0
        // and index of element < size of array
        else {
            while ((x > 0) && (g < n - 1)) {
                g++;
                x--;
            }
 
            // Check if reached the size of the array
            // and x > 0 the smaller index
            // is decremented
            if (x > 0) {
                while ((x > 0) && (h > 0)) {
                    h--;
                    x--;
                }
            }
            cout << g - h << endl;
        }
    }
}
 
// Driver code
int main()
{
    int a[] = { 100, 33, 10, 1 };
    int x = 5, A = 100, B = 1;
    int n = sizeof(a) / sizeof(a[0]);
    max_distance(a, n, x, A, B);
    return 0;
}

Java




// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to maximize the distance
// between the two elements of the
// array by at most X swaps
static void max_distance(int a[], int n, int x,
                         int A, int B)
{
     
    // Initialize the variables
    int i, g = 0, h = 0;
 
    // Iterate till the length of the array
    for(i = 0; i < n; i++)
    {
         
        // Check if current element is A
        if (a[i] == A)
         
            // Store index
            g = i;
 
        // Check if current element is B
        if (a[i] == B)
         
            // Store index
            h = i;
    }
 
    // If X = 0, swapping can not be done
    if (x == 0)
    {
        System.out.print(Math.abs(g - h));
    }
 
    // If elements are at starting and
    // ending indices, then the distance
    // is already maximum
    else if ((g == 0) && (h == (n - 1)))
        System.out.println(n - 1);
 
    else if ((g == n - 1) && (h == 0))
        System.out.println(n - 1);
 
    else
    {
         
        // Greater index is incremented
        // till x > 0 and theindex of
        // element < size of array
        if (h > g)
        {
            while ((x > 0) && (h < n - 1))
            {
                h++;
                x--;
            }
 
            // Check if reached the size of
            // array and x > 0, then the
            // smaller index is decremented
            if (x > 0)
            {
                while ((x > 0) && (g > 0))
                {
                    g--;
                    x--;
                }
            }
            System.out.println(h - g);
        }
 
        // Greater index is incremented till x>0
        // and index of element < size of array
        else
        {
            while ((x > 0) && (g < n - 1))
            {
                g++;
                x--;
            }
 
            // Check if reached the size of the array
            // and x > 0 the smaller index
            // is decremented
            if (x > 0)
            {
                while ((x > 0) && (h > 0))
                {
                    h--;
                    x--;
                }
            }
            System.out.println(g - h);
        }
    }
}
 
// Driver code
public static void main (String []args)
{
    int a[] = { 100, 33, 10, 1 };
    int x = 5, A = 100, B = 1;
    int n = a.length;
     
    max_distance(a, n, x, A, B);
}
}
 
// This code is contributed by chitranayal

Python3




# Python3 program for the above approach
 
# Function to maximize the distance
# between the two elements of the
# array by at most X swaps
def max_distance(a, n, x, A, B):
     
    # Initialize the variables
    g = 0
    h = 0
     
    for i in range(0, n):
         
        # Check if current element is A
        if (a[i] == A):
             
            # Store index
            g = i
             
        # Check if current element is B
        if (a[i] == B):
             
            # Store index
            h = i
             
    # If X = 0, swapping can not be done
    if (x == 0):
        print(abs(g - h))
         
    # If elements are at starting and
    # ending indices, then the distance
    # is already maximum
    elif ((g == 0) and (h == (n - 1))):
        print(n - 1, end = '')
         
    elif ((g == n - 1) and (h == 0)):
        print(n - 1, end = '')
    else:
         
        # Greater index is incremented
        # till x > 0 and the
        # index of element < size of array
        if (h > g):
            while ((x > 0) and (h < n - 1)):
                h += 1
                x -= 1
                 
                # Check if reached the size
                # of array and x > 0, then the
                # smaller index is decremented
                if (x > 0):
                    while ((x > 0) and (g > 0)):
                        g -= 1
                        x -= 1
                         
                print(h - g, end = '')
                 
        # Greater index is incremented till x>0
        # and index of element < size of array
        else:
            while ((x > 0) and (g < n - 1)):
                g += 1
                x -= 1
                 
            # Check if reached the size of
            # the array and x > 0 the smaller
            # index is decremented
            if (x > 0):
                while ((x > 0) and (h > 0)):
                    h -= 1
                    x -= 1
                     
            print(g - h, end = '')
             
# Driver code
if __name__ == '__main__':
     
    a = [ 100, 33, 10, 1 ]
    x = 5
    A = 100
    B = 1
    n = len(a)
     
    max_distance(a, n, x, A, B)
                     
# This code is contributed by virusbuddah_    

C#




// C# program for the above approach
using System;
 
class GFG{
 
// Function to maximize the distance
// between the two elements of the
// array by at most X swaps
static void max_distance(int []a, int n, int x,
                         int A, int B)
{
     
    // Initialize the variables
    int i, g = 0, h = 0;
 
    // Iterate till the length of the array
    for(i = 0; i < n; i++)
    {
         
        // Check if current element is A
        if (a[i] == A)
         
            // Store index
            g = i;
 
        // Check if current element is B
        if (a[i] == B)
         
            // Store index
            h = i;
    }
 
    // If X = 0, swapping can not be done
    if (x == 0)
    {
        Console.Write(Math.Abs(g - h));
    }
 
    // If elements are at starting and
    // ending indices, then the distance
    // is already maximum
    else if ((g == 0) && (h == (n - 1)))
        Console.WriteLine(n - 1);
 
    else if ((g == n - 1) && (h == 0))
        Console.WriteLine(n - 1);
 
    else
    {
         
        // Greater index is incremented
        // till x > 0 and theindex of
        // element < size of array
        if (h > g)
        {
            while ((x > 0) && (h < n - 1))
            {
                h++;
                x--;
            }
 
            // Check if reached the size of
            // array and x > 0, then the
            // smaller index is decremented
            if (x > 0)
            {
                while ((x > 0) && (g > 0))
                {
                    g--;
                    x--;
                }
            }
            Console.WriteLine(h - g);
        }
 
        // Greater index is incremented till x>0
        // and index of element < size of array
        else
        {
            while ((x > 0) && (g < n - 1))
            {
                g++;
                x--;
            }
 
            // Check if reached the size of the
            // array and x > 0 the smaller index
            // is decremented
            if (x > 0)
            {
                while ((x > 0) && (h > 0))
                {
                    h--;
                    x--;
                }
            }
            Console.WriteLine(g - h);
        }
    }
}
 
// Driver code
public static void Main(String []args)
{
    int []a = { 100, 33, 10, 1 };
    int x = 5, A = 100, B = 1;
    int n = a.Length;
     
    max_distance(a, n, x, A, B);
}
}
 
// This code is contributed by Amit Katiyar

Javascript




<script>
 
// JavaScript program for the above approach
 
// Function to maximize the distance
// between the two elements of the
// array by at most X swaps
function max_distance(a,n,x,A,B)
{
    // Initialize the variables
    let i, g = 0, h = 0;
   
    // Iterate till the length of the array
    for(i = 0; i < n; i++)
    {
           
        // Check if current element is A
        if (a[i] == A)
           
            // Store index
            g = i;
   
        // Check if current element is B
        if (a[i] == B)
           
            // Store index
            h = i;
    }
   
    // If X = 0, swapping can not be done
    if (x == 0)
    {
        document.write(Math.abs(g - h));
    }
   
    // If elements are at starting and
    // ending indices, then the distance
    // is already maximum
    else if ((g == 0) && (h == (n - 1)))
        document.write(n - 1);
   
    else if ((g == n - 1) && (h == 0))
        document.write(n - 1);
   
    else
    {
           
        // Greater index is incremented
        // till x > 0 and theindex of
        // element < size of array
        if (h > g)
        {
            while ((x > 0) && (h < n - 1))
            {
                h++;
                x--;
            }
   
            // Check if reached the size of
            // array and x > 0, then the
            // smaller index is decremented
            if (x > 0)
            {
                while ((x > 0) && (g > 0))
                {
                    g--;
                    x--;
                }
            }
            document.write(h - g);
        }
   
        // Greater index is incremented till x>0
        // and index of element < size of array
        else
        {
            while ((x > 0) && (g < n - 1))
            {
                g++;
                x--;
            }
   
            // Check if reached the size of the array
            // and x > 0 the smaller index
            // is decremented
            if (x > 0)
            {
                while ((x > 0) && (h > 0))
                {
                    h--;
                    x--;
                }
            }
            document.write(g - h);
        }
    }
}
 
// Driver code
let a=[ 100, 33, 10, 1];
let x = 5, A = 100, B = 1;
let  n = a.length;
max_distance(a, n, x, A, B);
 
 
// This code is contributed by rag2127
 
</script>
Output: 
3

 

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.




My Personal Notes arrow_drop_up
Recommended Articles
Page :