Largest lexicographic array with at-most K consecutive swaps

13 Sep, 2021
Given an array arr[], find the lexicographically largest array that can be obtained by performing at-most k consecutive swaps. 
Examples : 
Input : arr[] = {3, 5, 4, 1, 2}
        k = 3
Output : 5, 4, 3, 2, 1
Explanation : Array given : 3 5 4 1 2
After swap 1 : 5 3 4 1 2
After swap 2 : 5 4 3 1 2
After swap 3 : 5 4 3 2 1

Input : arr[] = {3, 5, 1, 2, 1}
        k = 3
Output : 5, 3, 2, 1, 1
Brute Force Approach : Generate all permutation of the array and then pick the one which satisfies the condition of at most K swaps. The time complexity of this approach is O(n!).
Optimized Approach : In this greedy approach, first find the largest element present in the array which is greater than(if the 1st position element is not the greatest) the 1st position and which can be placed at the 1st position with at-most K swaps. After finding that element, note its index. Then, swap elements of the array and update K value. Apply this procedure for other positions till k is non-zero or array becomes lexicographically largest.
Below is the implementation of above approach : 
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find lexicographically// maximum value after k swaps.#include <bits/stdc++.h>using namespace std; // Function which modifies the arrayvoid KSwapMaximum(int arr[], int n, int k){    for (int i = 0; i < n - 1 && k > 0; ++i) {         // Here, indexPosition is set where we        // want to put the current largest integer        int indexPosition = i;        for (int j = i + 1; j < n; ++j) {             // If we exceed the Max swaps            // then break the loop            if (k <= j - i)                break;             // Find the maximum value from i+1 to            // max k or n which will replace            // arr[indexPosition]            if (arr[j] > arr[indexPosition])                indexPosition = j;        }         // Swap the elements from Maximum indexPosition        // we found till now to the ith index        for (int j = indexPosition; j > i; --j)            swap(arr[j], arr[j - 1]);         // Updates k after swapping indexPosition-i        // elements        k -= indexPosition - i;    }} // Driver codeint main(){    int arr[] = { 3, 5, 4, 1, 2 };    int n = sizeof(arr) / sizeof(arr[0]);    int k = 3;     KSwapMaximum(arr, n, k);     // Print the final Array    for (int i = 0; i < n; ++i)        cout << arr[i] << " ";}
// Java program to find// lexicographically// maximum value after// k swaps.import java.io.*; class GFG{    static void SwapInts(int array[],                         int position1,                         int position2)    {        // Swaps elements        // in an array.                 // Copy the first        // position's element        int temp = array[position1];                 // Assign to the        // second element        array[position1] = array[position2];                 // Assign to the        // first element        array[position2] = temp;    }         // Function which    // modifies the array    static void KSwapMaximum(int []arr,                             int n, int k)    {        for (int i = 0;                 i < n - 1 && k > 0; ++i)        {                 // Here, indexPosition            // is set where we want to            // put the current largest            // integer            int indexPosition = i;            for (int j = i + 1; j < n; ++j)            {                     // If we exceed the                // Max swaps then                // break the loop                if (k <= j - i)                    break;                     // Find the maximum value                // from i+1 to max k or n                // which will replace                // arr[indexPosition]                if (arr[j] > arr[indexPosition])                    indexPosition = j;            }                 // Swap the elements from            // Maximum indexPosition            // we found till now to            // the ith index            for (int j = indexPosition; j > i; --j)                SwapInts(arr, j, j - 1);                 // Updates k after swapping            // indexPosition-i elements            k -= indexPosition - i;        }    }         // Driver code    public static void main(String args[])    {        int []arr = { 3, 5, 4, 1, 2 };        int n = arr.length;        int k = 3;             KSwapMaximum(arr, n, k);             // Print the final Array        for (int i = 0; i < n; ++i)            System.out.print(arr[i] + " ");    }} // This code is contributed by// Manish Shaw(manishshaw1)
# Python program to find# lexicographically# maximum value after# k swaps. arr = [3, 5, 4, 1, 2] # Function which# modifies the arraydef KSwapMaximum(n, k) :         global arr    for i in range(0, n - 1) :        if (k > 0) :                     # Here, indexPosition            # is set where we want to            # put the current largest            # integer            indexPosition = i            for j in range(i + 1, n) :                             # If we exceed the Max swaps                # then break the loop                if (k <= j - i) :                    break                     # Find the maximum value                # from i+1 to max k or n                # which will replace                # arr[indexPosition]                if (arr[j] > arr[indexPosition]) :                    indexPosition = j                         # Swap the elements from            # Maximum indexPosition            # we found till now to            # the ith index            for j in range(indexPosition, i, -1) :                t = arr[j]                arr[j] = arr[j - 1]                arr[j - 1] = t                 # Updates k after swapping            # indexPosition-i elements            k = k - indexPosition - i # Driver coden = len(arr)k = 3 KSwapMaximum(n, k) # Print the final Arrayfor i in range(0, n) :    print ("{} " .            format(arr[i]),                 end = "")     # This code is contributed by# Manish Shaw(manishshaw1)
// C# program to find// lexicographically// maximum value after// k swaps.using System; class GFG{    static void SwapInts(int[] array,                         int position1,                         int position2)    {        // Swaps elements in an array.                 // Copy the first position's element        int temp = array[position1];                 // Assign to the second element        array[position1] = array[position2];                 // Assign to the first element        array[position2] = temp;    }         // Function which    // modifies the array    static void KSwapMaximum(int []arr,                             int n, int k)    {        for (int i = 0;                 i < n - 1 && k > 0; ++i)        {                 // Here, indexPosition            // is set where we want to            // put the current largest            // integer            int indexPosition = i;            for (int j = i + 1; j < n; ++j)            {                     // If we exceed the                // Max swaps then                // break the loop                if (k <= j - i)                    break;                     // Find the maximum value                // from i+1 to max k or n                // which will replace                // arr[indexPosition]                if (arr[j] > arr[indexPosition])                    indexPosition = j;            }                 // Swap the elements from            // Maximum indexPosition            // we found till now to            // the ith index            for (int j = indexPosition; j > i; --j)                SwapInts(arr, j, j - 1);                 // Updates k after swapping            // indexPosition-i elements            k -= indexPosition - i;        }    }         // Driver code    static void Main()    {        int []arr = new int[]{ 3, 5, 4, 1, 2 };        int n = arr.Length;        int k = 3;             KSwapMaximum(arr, n, k);             // Print the final Array        for (int i = 0; i < n; ++i)            Console.Write(arr[i] + " ");    }}// This code is contributed by// Manish Shaw(manishshaw1)
<?php// PHP program to find// lexicographically// maximum value after// k swaps. function swap(&$x, &$y){    $x ^= $y ^= $x ^= $y;} // Function which// modifies the arrayfunction KSwapMaximum(&$arr, $n, $k){    for ($i = 0;         $i < $n - 1 &&         $k > 0; $i++)    {                 // Here, indexPosition        // is set where we want to        // put the current largest        // integer        $indexPosition = $i;        for ($j = $i + 1;             $j < $n; $j++)        {             // If we exceed the Max swaps            // then break the loop            if ($k <= $j - $i)                break;             // Find the maximum value            // from i+1 to max k or n            // which will replace            // arr[indexPosition]            if ($arr[$j] > $arr[$indexPosition])                $indexPosition = $j;        }                 // Swap the elements from        // Maximum indexPosition        // we found till now to        // the ith index        for ($j = $indexPosition;             $j > $i; $j--)            swap($arr[$j], $arr[$j - 1]);         // Updates k after swapping        // indexPosition-i elements        $k -= $indexPosition - $i;    }} // Driver code$arr = array( 3, 5, 4, 1, 2 );$n = count($arr);$k = 3; KSwapMaximum($arr, $n, $k); // Print the final Arrayfor ($i = 0; $i < $n; $i++)    echo ($arr[$i]." ");     // This code is contributed by// Manish Shaw(manishshaw1)?>
<script> // JavaScript program to find// lexicographically// maximum value after// k swaps.     function SwapLets(array, position1, position2)    {        // Swaps elements        // in an array.                   // Copy the first        // position's element        let temp = array[position1];                   // Assign to the        // second element        array[position1] = array[position2];                   // Assign to the        // first element        array[position2] = temp;    }           // Function which    // modifies the array    function KSwapMaximum(arr, n, k)    {        for (let i = 0;                 i < n - 1 && k > 0; ++i)        {                   // Here, indexPosition            // is set where we want to            // put the current largest            // integer            let indexPosition = i;            for (let j = i + 1; j < n; ++j)            {                       // If we exceed the                // Max swaps then                // break the loop                if (k <= j - i)                    break;                       // Find the maximum value                // from i+1 to max k or n                // which will replace                // arr[indexPosition]                if (arr[j] > arr[indexPosition])                    indexPosition = j;            }                   // Swap the elements from            // Maximum indexPosition            // we found till now to            // the ith index            for (let j = indexPosition; j > i; --j)                SwapLets(arr, j, j - 1);                   // Updates k after swapping            // indexPosition-i elements            k -= indexPosition - i;        }    } // Driver code             let arr = [ 3, 5, 4, 1, 2 ];        let n = arr.length;        let k = 3;               KSwapMaximum(arr, n, k);               // Print the final Array        for (let i = 0; i < n; ++i)            document.write(arr[i] + " ");                 // This code is contributed by coode_hunt.</script>
5 4 3 1 2
 
Time Complexity: O(N*N) Auxiliary Space: O(1) 
manishshaw1
nidhi_biet
code_hunt
ankita_saini
arorakashish0911
lexicographic-ordering
Arrays
Greedy
Arrays
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Python | Using 2D arrays/lists the right way
Find Second largest element in an array
Introduction to Data Structures
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Huffman Coding | Greedy Algo-3