Maximum number formed from array with K number of adjacent swaps allowed

Given an array a[ ] and the number of adjacent swap operations allowed are K. The task is to find the max number that can be formed using these swap operations.Â
Examples:Â
Input : a[]={ 1, 2, 9, 8, 1, 4, 9, 9, 9 }, K = 4Â
Output : 9 8 1 2 1 4 9 9 9Â
After 1st swap a[ ] becomes 1 9 2 8 1 4 9 9 9Â
After 2nd swap a[ ] becomes 9 1 2 8 1 4 9 9 9Â
After 3rd swap a[ ] becomes 9 1 8 2 1 4 9 9 9Â
After 4th swap a[ ] becomes 9 8 1 2 1 4 9 9 9Input : a[]={2, 5, 8, 7, 9}, K = 2Â
Output : 8 2 5 7 9Â
Approach:Â
- Starting from the first digit, check for the next K digits and store the index of the largest number.
- Bring that greatest digit to the top by swapping the adjacent digits.
- Reduce to the value of K by the number of adjacent swaps done.
- Repeat the above steps until the number of swaps becomes zero.
Below is the implementation of the above approachÂ
C++
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std;Â
// Function to print the// elements of the arrayvoid print(int arr[], int n){Â Â Â Â for (int i = 0; i < n; i++) {Â Â Â Â Â Â Â Â cout << arr[i] << " ";Â Â Â Â }Â Â Â Â cout << endl;}Â
// Exchange array elements one by// one from right to left side// starting from the current position// and ending at the target positionvoid swapMax(int* arr, int target_position,                      int current_position){    int aux = 0;    for (int i = current_position;         i > target_position; i--) {        aux = arr[i - 1];        arr[i - 1] = arr[i];        arr[i] = aux;    }}Â
// Function to return the// maximum number arrayvoid maximizeArray(int* arr,                   int length, int swaps){    // Base condition    if (swaps == 0)        return;Â
    // Start from the first index    for (int i = 0; i < length; i++) {        int max_index = 0, max = INT_MIN;Â
        // Search for the next K elements        int limit = (swaps + i) > length ?                         length : swaps + i;Â
        // Find index of the maximum        // element in next K elements        for (int j = i; j <= limit; j++) {            if (arr[j] > max) {                max = arr[j];                max_index = j;            }        }Â
        // Update the value of        // number of swaps        swaps -= (max_index - i);Â
        // Update the array elements by        // swapping adjacent elements        swapMax(arr, i, max_index);Â
        if (swaps == 0)            break;    }}Â
// Driver codeint main(){Â Â Â Â int arr[] = { 1, 2, 9, 8, 1, 4, 9, 9, 9 };Â Â Â Â int length = sizeof(arr) / sizeof(int);Â Â Â Â int swaps = 4;Â Â Â Â maximizeArray(arr, length, swaps);Â
    print(arr, length);Â
    return 0;} |
Java
// Java implementation of the above approachclass GFG{Â
// Function to print the// elements of the arraystatic void print(int arr[], int n){Â Â Â Â for (int i = 0; i < n; i++)Â Â Â Â {Â Â Â Â Â Â Â Â System.out.print(arr[i] + " ");Â Â Â Â }Â Â Â Â System.out.println();}Â
// Exchange array elements one by// one from right to left side// starting from the current position// and ending at the target positionstatic void swapMax(int[] arr, int target_position,                    int current_position){    int aux = 0;    for (int i = current_position;        i > target_position; i--)     {        aux = arr[i - 1];        arr[i - 1] = arr[i];        arr[i] = aux;    }}Â
// Function to return the// maximum number arraystatic void maximizeArray(int[] arr,                int length, int swaps){    // Base condition    if (swaps == 0)        return;Â
    // Start from the first index    for (int i = 0; i < length; i++)     {        int max_index = 0, max = Integer.MIN_VALUE;Â
        // Search for the next K elements        int limit = (swaps + i) > length ?                         length : swaps + i;Â
        // Find index of the maximum        // element in next K elements        for (int j = i; j <= limit; j++)         {            if (arr[j] > max)             {                max = arr[j];                max_index = j;            }        }Â
        // Update the value of        // number of swaps        swaps -= (max_index - i);Â
        // Update the array elements by        // swapping adjacent elements        swapMax(arr, i, max_index);Â
        if (swaps == 0)            break;    }}Â
// Driver codepublic static void main(String[] args) {Â Â Â Â int arr[] = { 1, 2, 9, 8, 1, 4, 9, 9, 9 };Â Â Â Â int length = arr.length;Â Â Â Â int swaps = 4;Â Â Â Â maximizeArray(arr, length, swaps);Â
    print(arr, length);}}Â
/* This code is contributed by PrinciRaj1992 */ |
Python3
# Python3 implementation of the above approach import sysÂ
# Function to print the # elements of the array def print_ele(arr, n) :Â Â Â Â Â Â Â Â Â for i in range(n) :Â Â Â Â Â Â Â Â print(arr[i],end=" "); Â Â Â Â Â Â Â Â Â Â Â Â Â print(); Â
# Exchange array elements one by # one from right to left side # starting from the current position # and ending at the target position def swapMax(arr, target_position, Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â current_position) :Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â aux = 0; Â Â Â Â for i in range(current_position, target_position,-1) :Â Â Â Â Â Â Â Â aux = arr[i - 1]; Â Â Â Â Â Â Â Â arr[i - 1] = arr[i]; Â Â Â Â Â Â Â Â arr[i] = aux; Â
# Function to return the # maximum number array def maximizeArray(arr, length, swaps) : Â
    # Base condition     if (swaps == 0) :        return; Â
    # Start from the first index     for i in range(length) :        max_index = 0; max = -(sys.maxsize-1);                 # Search for the next K elements        if (swaps + i) > length :            limit = length        else:            limit = swaps + i                     # Find index of the maximum        # element in next K elements        for j in range(i, limit + 1) :            if (arr[j] > max) :                max = arr[j];                max_index = j;                         # Update the value of        # number of swaps        swaps -= (max_index - i); Â
        # Update the array elements by         # swapping adjacent elements         swapMax(arr, i, max_index); Â
        if (swaps == 0) :            break; Â
# Driver code if __name__ == "__main__" : Â
    arr = [ 1, 2, 9, 8, 1, 4, 9, 9, 9 ];     length = len(arr);     swaps = 4;     maximizeArray(arr, length, swaps); Â
    print_ele(arr, length); Â
# This code is contributed by AnkitRai01 |
C#
// C# program to find the sum // and product of k smallest and // k largest prime numbers in an array Â
using System;Â Â Â Â Â class GFG{Â
// Function to print the// elements of the arraystatic void print(int []arr, int n){Â Â Â Â for (int i = 0; i < n; i++)Â Â Â Â {Â Â Â Â Â Â Â Â Console.Write(arr[i] + " ");Â Â Â Â }Â Â Â Â Console.WriteLine();}Â
// Exchange array elements one by// one from right to left side// starting from the current position// and ending at the target positionstatic void swapMax(int[] arr, int target_position,                    int current_position){    int aux = 0;    for (int i = current_position;        i > target_position; i--)     {        aux = arr[i - 1];        arr[i - 1] = arr[i];        arr[i] = aux;    }}Â
// Function to return the// maximum number arraystatic void maximizeArray(int[] arr,                int length, int swaps){    // Base condition    if (swaps == 0)        return;Â
    // Start from the first index    for (int i = 0; i < length; i++)     {        int max_index = 0, max = int.MinValue;Â
        // Search for the next K elements        int limit = (swaps + i) > length ?                         length : swaps + i;Â
        // Find index of the maximum        // element in next K elements        for (int j = i; j <= limit; j++)         {            if (arr[j] > max)             {                max = arr[j];                max_index = j;            }        }Â
        // Update the value of        // number of swaps        swaps -= (max_index - i);Â
        // Update the array elements by        // swapping adjacent elements        swapMax(arr, i, max_index);Â
        if (swaps == 0)            break;    }}Â
// Driver codepublic static void Main(String[] args) {Â Â Â Â int []arr = { 1, 2, 9, 8, 1, 4, 9, 9, 9 };Â Â Â Â int length = arr.Length;Â Â Â Â int swaps = 4;Â Â Â Â maximizeArray(arr, length, swaps);Â
    print(arr, length);}}Â
/* This code is contributed by PrinciRaj1992 */ |
Javascript
<script>Â
// JavaScript implementation of the above approachÂ
Â
// Function to print the// elements of the arrayfunction print(arr, n) {Â Â Â Â for (let i = 0; i < n; i++) {Â Â Â Â Â Â Â Â document.write(arr[i] + " ");Â Â Â Â }Â Â Â Â document.write("<br>");}Â
// Exchange array elements one by// one from right to left side// starting from the current position// and ending at the target positionfunction swapMax(arr, target_position, current_position) {Â Â Â Â let aux = 0;Â Â Â Â for (let i = current_position; i > target_position; i--) {Â Â Â Â Â Â Â Â aux = arr[i - 1];Â Â Â Â Â Â Â Â arr[i - 1] = arr[i];Â Â Â Â Â Â Â Â arr[i] = aux;Â Â Â Â }}Â
// Function to return the// maximum number arrayfunction maximizeArray(arr, length, swaps) {    // Base condition    if (swaps == 0)        return;Â
    // Start from the first index    for (let i = 0; i < length; i++) {        let max_index = 0, max = Number.MIN_SAFE_INTEGER;Â
        // Search for the next K elements        let limit = (swaps + i) > length ?            length : swaps + i;Â
        // Find index of the maximum        // element in next K elements        for (let j = i; j <= limit; j++) {            if (arr[j] > max) {                max = arr[j];                max_index = j;            }        }Â
        // Update the value of        // number of swaps        swaps -= (max_index - i);Â
        // Update the array elements by        // swapping adjacent elements        swapMax(arr, i, max_index);Â
        if (swaps == 0)            break;    }}Â
// Driver codeÂ
let arr = [1, 2, 9, 8, 1, 4, 9, 9, 9];let length = arr.length;let swaps = 4;maximizeArray(arr, length, swaps);Â
print(arr, length);Â
// This code is contributed by gfgkingÂ
</script> |
Output:Â
9 8 1 2 1 4 9 9 9
Â
Time Complexity: O(N*N) where N is the length of given array.
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!


