📜  最多 k 次交换后的最大排列

📅  最后修改于: 2021-10-26 05:33:23             🧑  作者: Mango

给定前n 个自然数的排列作为数组和一个整数k 。在最多k 次交换后打印字典序最大的排列

例子:

Input: arr[] = {4, 5, 2, 1, 3}
       k = 3
Output: 5 4 3 2 1
Swap 1st and 2nd elements: 5 4 2 1 3 
Swap 3rd and 5th elements: 5 4 3 1 2 
Swap 4th and 5th elements: 5 4 3 2 1 

Input: arr[] = {2, 1, 3}
       k = 1
Output: 3 1 2
Swap 1st and 3re elements: 3 1 2

朴素的方法这个想法是按字典序递减顺序生成一个一个的排列。将每个生成的排列与原始数组进行比较,并计算转换所需的交换次数。如果计数小于或等于 k,则打印此排列。这种方法的问题是实现起来比较困难,并且肯定会因为 N 的大值而超时。

算法:

  1. 要找到将一个数组转换为另一个数组的最小交换,请阅读本文。
  2. 复制原始数组并按降序对该数组进行排序。所以排序后的数组是原始数组的最大排列。
  3. 现在按字典顺序生成所有排列。使用prev_permutation()函数计算先前的排列。
  4. 如果计数小于或等于 k,找出将新数组(按降序排列)转换为原始数组所需的最小步骤。然后打印数组并中断。
C++14
#include 
using namespace std;
 
// Function returns the minimum number
// of swaps required to sort the array
// This method is taken from below post
// https:// www.geeksforgeeks.org/
// minimum-number-swaps-required-sort-array/
int minSwapsToSort(int arr[], int n)
{
    // Create an array of pairs where first
    // element is array element and second
    // element is position of first element
    pair arrPos[n];
    for (int i = 0; i < n; i++) {
        arrPos[i].first = arr[i];
        arrPos[i].second = i;
    }
 
    // Sort the array by array element
    // values to get right position of
    // every element as second
    // element of pair.
    sort(arrPos, arrPos + n);
 
    // To keep track of visited elements.
    // Initialize all elements as not
    // visited or false.
    vector vis(n, false);
 
    // Initialize result
    int ans = 0;
 
    // Traverse array elements
    for (int i = 0; i < n; i++) {
        // Already swapped and corrected or
        // already present at correct pos
        if (vis[i] || arrPos[i].second == i)
            continue;
 
        // Find out the number of  node in
        // this cycle and add in ans
        int cycle_size = 0;
        int j = i;
        while (!vis[j]) {
            vis[j] = 1;
 
            // move to next node
            j = arrPos[j].second;
            cycle_size++;
        }
 
        // Update answer by adding current
        // cycle.
        ans += (cycle_size - 1);
    }
 
    // Return result
    return ans;
}
 
// method returns minimum number of
// swap to make array B same as array A
int minSwapToMakeArraySame(
    int a[], int b[], int n)
{
    // Map to store position of elements
    // in array B we basically store
    // element to index mapping.
    map mp;
    for (int i = 0; i < n; i++)
        mp[b[i]] = i;
 
    // now we're storing position of array
    // A elements in array B.
    for (int i = 0; i < n; i++)
        b[i] = mp[a[i]];
 
    /* We can uncomment this section to
      print modified b array
    for (int i = 0; i < N; i++)
        cout << b[i] << " ";
    cout << endl; */
 
    // Returing minimum swap for sorting
    // in modified array B as final answer
    return minSwapsToSort(b, n);
}
 
// Function to calculate largest
// permutation after atmost K swaps
void KswapPermutation(
    int arr[], int n, int k)
{
    int a[n];
 
    // copy the array
    for (int i = 0; i < n; i++)
        a[i] = arr[i];
 
    // Sort the array in descending order
    sort(arr, arr + n, greater());
 
    // generate permutation in lexicographically
    // decreasing order.
    do {
        // copy the array
        int a1[n], b1[n];
        for (int i = 0; i < n; i++) {
            a1[i] = arr[i];
            b1[i] = a[i];
        }
 
        // Check if it can be made same in k steps
        if (
            minSwapToMakeArraySame(
                a1, b1, n)
            <= k) {
            // Print the array
            for (int i = 0; i < n; i++)
                cout << arr[i] << " ";
            break;
        }
 
        // move to previous permutation
    } while (prev_permutation(arr, arr + n));
}
 
int main()
{
    int arr[] = { 4, 5, 2, 1, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    cout << "Largest permutation after "
         << k << " swaps:\n";
 
    KswapPermutation(arr, n, k);
    return 0;
}


C++
// Below is C++ code to print largest
// permutation after at most K swaps
#include 
using namespace std;
 
// Function to calculate largest
// permutation after atmost K swaps
void KswapPermutation(
    int arr[], int n, int k)
{
    // Auxiliary dictionary of
    // storing the position of elements
    int pos[n + 1];
 
    for (int i = 0; i < n; ++i)
        pos[arr[i]] = i;
 
    for (int i = 0; i < n && k; ++i) {
        // If element is already i'th largest,
        // then no need to swap
        if (arr[i] == n - i)
            continue;
 
        // Find position of i'th
        // largest value, n-i
        int temp = pos[n - i];
 
        // Swap the elements position
        pos[arr[i]] = pos[n - i];
        pos[n - i] = i;
 
        // Swap the ith largest value with the
        // current value at ith place
        swap(arr[temp], arr[i]);
 
        // decrement number of swaps
        --k;
    }
}
 
// Driver code
int main()
{
    int arr[] = { 4, 5, 2, 1, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    KswapPermutation(arr, n, k);
    cout << "Largest permutation after "
         << k << " swaps:n";
    for (int i = 0; i < n; ++i)
        printf("%d ", arr[i]);
    return 0;
}


Java
// Below is Java code to print
// largest permutation after
// atmost K swaps
class GFG {
 
    // Function to calculate largest
    // permutation after atmost K swaps
    static void KswapPermutation(
        int arr[], int n, int k)
    {
 
        // Auxiliary dictionary of storing
        // the position of elements
        int pos[] = new int[n + 1];
 
        for (int i = 0; i < n; ++i)
            pos[arr[i]] = i;
 
        for (int i = 0; i < n && k > 0; ++i) {
 
            // If element is already i'th
            // largest, then no need to swap
            if (arr[i] == n - i)
                continue;
 
            // Find position of i'th largest
            // value, n-i
            int temp = pos[n - i];
 
            // Swap the elements position
            pos[arr[i]] = pos[n - i];
            pos[n - i] = i;
 
            // Swap the ith largest value with the
            // current value at ith place
            int tmp1 = arr[temp];
            arr[temp] = arr[i];
            arr[i] = tmp1;
 
            // decrement number of swaps
            --k;
        }
    }
 
    // Driver method
    public static void main(String[] args)
    {
 
        int arr[] = { 4, 5, 2, 1, 3 };
        int n = arr.length;
        int k = 3;
 
        KswapPermutation(arr, n, k);
 
        System.out.print(
            "Largest permutation "
            + "after " + k + " swaps:\n");
 
        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
    }
}
 
// This code is contributed by Anant Agarwal.


Python
# Python code to print largest permutation after K swaps
 
def KswapPermutation(arr, n, k):
 
    # Auxiliary array of storing the position of elements
    pos = {}
    for i in range(n):
        pos[arr[i]] = i
 
    for i in range(n):
 
        # If K is exhausted then break the loop
        if k == 0:
            break
 
        # If element is already largest then no need to swap
        if (arr[i] == n-i):
            continue
 
        # Find position of i'th largest value, n-i
        temp = pos[n-i]
 
        # Swap the elements position
        pos[arr[i]] = pos[n-i]
        pos[n-i] = i
 
        # Swap the ith largest value with the value at
        # ith place
        arr[temp], arr[i] = arr[i], arr[temp]
 
        # Decrement K after swap
        k = k-1
 
# Driver code
arr = [4, 5, 2, 1, 3]
n = len(arr)
k = 3
KswapPermutation(arr, N, K)
 
# Print the answer
print "Largest permutation after", K, "swaps: "
print " ".join(map(str, arr))


C#
// Below is C# code to print largest
// permutation after atmost K swaps.
using System;
 
class GFG {
 
    // Function to calculate largest
    // permutation after atmost K
    // swaps
    static void KswapPermutation(int[] arr,
                                 int n, int k)
    {
 
        // Auxiliary dictionary of storing
        // the position of elements
        int[] pos = new int[n + 1];
 
        for (int i = 0; i < n; ++i)
            pos[arr[i]] = i;
 
        for (int i = 0; i < n && k > 0; ++i) {
 
            // If element is already i'th
            // largest, then no need to swap
            if (arr[i] == n - i)
                continue;
 
            // Find position of i'th largest
            // value, n-i
            int temp = pos[n - i];
 
            // Swap the elements position
            pos[arr[i]] = pos[n - i];
            pos[n - i] = i;
 
            // Swap the ith largest value with
            // the current value at ith place
            int tmp1 = arr[temp];
            arr[temp] = arr[i];
            arr[i] = tmp1;
 
            // decrement number of swaps
            --k;
        }
    }
 
    // Driver method
    public static void Main()
    {
 
        int[] arr = { 4, 5, 2, 1, 3 };
        int n = arr.Length;
        int k = 3;
 
        KswapPermutation(arr, n, k);
 
        Console.Write("Largest permutation "
                      + "after " + k + " swaps:\n");
 
        for (int i = 0; i < n; ++i)
            Console.Write(arr[i] + " ");
    }
}
 
// This code is contributed nitin mittal.


PHP


Javascript


C++
// C++ Program to find the
// largest permutation after
// at most k swaps using unordered_map.
#include 
#include 
using namespace std;
 
// Function to find the largest
// permutation after k swaps
void bestpermutation(
    int arr[], int k, int n)
{
    // Storing the elements and
    // their index in map
    unordered_map h;
    for (int i = 0; i < n; i++) {
        h.insert(make_pair(arr[i], i));
    }
 
    // If number of swaps allowed
    // are equal to number of elements
    // then the resulting permutation
    // will be descending order of
    // given permutation.
    if (n <= k) {
        sort(arr, arr + n, greater());
    }
    else {
 
        for (int j = n; j >= 1; j--) {
            if (k > 0) {
 
                int initial_index = h[j];
                int best_index = n - j;
 
                // if j is not at it's best index
                if (initial_index != best_index) {
 
                    h[j] = best_index;
 
                    // Change the index of the element
                    // which was at position 0. Swap
                    // the element basically.
                    int element = arr[best_index];
                    h[element] = initial_index;
                    swap(
                        arr[best_index],
                        arr[initial_index]);
 
                    // decrement number of swaps
                    k--;
                }
            }
        }
    }
}
 
// Driver code
int main()
{
    int arr[] = { 3, 1, 4, 2, 5 };
 
    // K is the number of swaps
    int k = 10;
 
    // n is the size of the array
    int n = sizeof(arr) / sizeof(int);
 
    // Function calling
    bestpermutation(arr, k, n);
 
    cout << "Largest possible permutation after "
         << k << " swaps is ";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
 
    return 0;
}
// This method is contributed by Kishan Mishra.


Java
// Java Program to find the
// largest permutation after
// at most k swaps using unordered_map.
import java.util.*;
class GFG
{
 
  // Function to find the largest
  // permutation after k swaps
  static void bestpermutation(ArrayList arr, int k, int n)
  {
 
    // Storing the elements and
    // their index in map
    HashMap h =  
      new HashMap(); 
    for (int i = 0; i < n; i++)
    {
      h.put(arr.get(i), i);
    }
 
    // If number of swaps allowed
    // are equal to number of elements
    // then the resulting permutation
    // will be descending order of
    // given permutation.
    if (n <= k) {
      Collections.sort(arr, Collections.reverseOrder()); 
    }
    else {
 
      for (int j = n; j >= 1; j--)
      {
        if (k > 0)
        {
 
          int initial_index = h.get(j);
          int best_index = n - j;
 
          // if j is not at it's best index
          if (initial_index != best_index)
          {
            h.put(j, best_index);
 
            // Change the index of the element
            // which was at position 0. Swap
            // the element basically.
            int element = arr.get(best_index);
            h.put(element, initial_index);
            int temp = arr.get(best_index);
            arr.set(best_index, arr.get(initial_index));
            arr.set(initial_index, temp);
 
            // decrement number of swaps
            k--;
          }
        }
      }
    }
  }
 
  // Driver code
  public static void main(String []args)
  {
 
    ArrayList arr = new ArrayList();
    arr.add(3);
    arr.add(1);
    arr.add(4);
    arr.add(2);
    arr.add(5);
 
    // K is the number of swaps
    int k = 10;
 
    // n is the size of the array
    int n = arr.size();
 
    // Function calling
    bestpermutation(arr, k, n);
 
    System.out.print("Largest possible permutation after " + k + " swaps is ");
 
    for (int i = 0; i < n; i++)
      System.out.print(arr.get(i) + " ");
  }
}
 
// This code is contributed by rutvik_56.


Python3
# Python3 program to find the
# largest permutation after
# at most k swaps using unordered_map.
 
# Function to find the largest
# permutation after k swaps
def bestpermutation(arr, k, n):
     
    # Storing the elements and
    # their index in map
    h = {}
    for i in range(n):
        h[arr[i]] = i
 
    # If number of swaps allowed
    # are equal to number of elements
    # then the resulting permutation
    # will be descending order of
    # given permutation.
    if (n <= k):
        arr.sort()
        arr.reverse()
    else:
         
        for j in range(n, 0, -1):
            if (k > 0):
                initial_index = h[j]
                best_index = n - j
 
                # If j is not at it's best index
                if (initial_index != best_index):
                    h[j] = best_index
 
                    # Change the index of the element
                    # which was at position 0. Swap
                    # the element basically.
                    element = arr[best_index]
                    h[element] = initial_index
                    arr[best_index], arr[initial_index] = (arr[initial_index],
                                                           arr[best_index])
                                                            
                    # Decrement number of swaps
                    k -= 1
 
# Driver Code
arr = [ 3, 1, 4, 2, 5 ]
 
# K is the number of swaps
k = 10
 
# n is the size of the array
n = len(arr)
 
# Function calling
bestpermutation(arr, k, n)
 
print("Largest possible permutation after",
      k, "swaps is", end = " ")
       
for i in range(n):
    print(arr[i], end = " ")
 
# This code is contributed by divyesh072019


C#
// C# Program to find the
// largest permutation after
// at most k swaps using unordered_map.
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to find the largest
    // permutation after k swaps
    static void bestpermutation(List arr, int k, int n)
    {
        // Storing the elements and
        // their index in map
        Dictionary h =  
                       new Dictionary(); 
        for (int i = 0; i < n; i++) {
            h.Add(arr[i], i);
        }
      
        // If number of swaps allowed
        // are equal to number of elements
        // then the resulting permutation
        // will be descending order of
        // given permutation.
        if (n <= k) {
            arr.Sort();
            arr.Reverse();
        }
        else {
      
            for (int j = n; j >= 1; j--) {
                if (k > 0) {
      
                    int initial_index = h[j];
                    int best_index = n - j;
      
                    // if j is not at it's best index
                    if (initial_index != best_index) {
      
                        h[j] = best_index;
      
                        // Change the index of the element
                        // which was at position 0. Swap
                        // the element basically.
                        int element = arr[best_index];
                        h[element] = initial_index;
                        int temp = arr[best_index];
                        arr[best_index] = arr[initial_index];
                        arr[initial_index] = temp;
      
                        // decrement number of swaps
                        k--;
                    }
                }
            }
        }
    }
 
  static void Main() {
    List arr = new List(new int[] {3, 1, 4, 2, 5 });
  
    // K is the number of swaps
    int k = 10;
  
    // n is the size of the array
    int n = arr.Count;
  
    // Function calling
    bestpermutation(arr, k, n);
  
    Console.Write("Largest possible permutation after " + k + " swaps is ");
    for (int i = 0; i < n; i++)
        Console.Write(arr[i] + " ");
  }
}
 
// This code is contributed by divyeshrabadiya07


Javascript


输出:

Largest permutation after 3 swaps:
5 4 3 2 1

复杂度分析:

  • 时间复杂度: O(N!)。
    生成所有排列需要 O(N!) 时间复杂度。
  • 空间复杂度: O(n)。
    存储新数组需要 O(n) 空间。

高效的方法这是一种贪婪的方法。当最大的元素位于数组的前面时,找到最大的排列,即最大的元素按降序排序。有至多为k互换所以把第1,2,3,…,在它们各自的位置k最大的元素。

注意:如果允许的交换次数等于数组的大小,则无需遍历整个数组。答案将只是反向排序的数组。

算法:

  1. 创建一个 HashMap 或长度为 n 的数组来存储元素索引对或将元素映射到其索引。
  2. 现在循环 k 次。
  3. 在每次迭代中,将第 i 个元素与元素 n – i 交换。其中 i 是循环的索引或计数。也交换他们的位置,即更新哈希图或数组。所以在这一步中,剩余元素中最大的元素被交换到前面。
  4. 打印输出数组。

实现 1:这使用简单的数组来获得解决方案。

C++

// Below is C++ code to print largest
// permutation after at most K swaps
#include 
using namespace std;
 
// Function to calculate largest
// permutation after atmost K swaps
void KswapPermutation(
    int arr[], int n, int k)
{
    // Auxiliary dictionary of
    // storing the position of elements
    int pos[n + 1];
 
    for (int i = 0; i < n; ++i)
        pos[arr[i]] = i;
 
    for (int i = 0; i < n && k; ++i) {
        // If element is already i'th largest,
        // then no need to swap
        if (arr[i] == n - i)
            continue;
 
        // Find position of i'th
        // largest value, n-i
        int temp = pos[n - i];
 
        // Swap the elements position
        pos[arr[i]] = pos[n - i];
        pos[n - i] = i;
 
        // Swap the ith largest value with the
        // current value at ith place
        swap(arr[temp], arr[i]);
 
        // decrement number of swaps
        --k;
    }
}
 
// Driver code
int main()
{
    int arr[] = { 4, 5, 2, 1, 3 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 3;
 
    KswapPermutation(arr, n, k);
    cout << "Largest permutation after "
         << k << " swaps:n";
    for (int i = 0; i < n; ++i)
        printf("%d ", arr[i]);
    return 0;
}

Java

// Below is Java code to print
// largest permutation after
// atmost K swaps
class GFG {
 
    // Function to calculate largest
    // permutation after atmost K swaps
    static void KswapPermutation(
        int arr[], int n, int k)
    {
 
        // Auxiliary dictionary of storing
        // the position of elements
        int pos[] = new int[n + 1];
 
        for (int i = 0; i < n; ++i)
            pos[arr[i]] = i;
 
        for (int i = 0; i < n && k > 0; ++i) {
 
            // If element is already i'th
            // largest, then no need to swap
            if (arr[i] == n - i)
                continue;
 
            // Find position of i'th largest
            // value, n-i
            int temp = pos[n - i];
 
            // Swap the elements position
            pos[arr[i]] = pos[n - i];
            pos[n - i] = i;
 
            // Swap the ith largest value with the
            // current value at ith place
            int tmp1 = arr[temp];
            arr[temp] = arr[i];
            arr[i] = tmp1;
 
            // decrement number of swaps
            --k;
        }
    }
 
    // Driver method
    public static void main(String[] args)
    {
 
        int arr[] = { 4, 5, 2, 1, 3 };
        int n = arr.length;
        int k = 3;
 
        KswapPermutation(arr, n, k);
 
        System.out.print(
            "Largest permutation "
            + "after " + k + " swaps:\n");
 
        for (int i = 0; i < n; ++i)
            System.out.print(arr[i] + " ");
    }
}
 
// This code is contributed by Anant Agarwal.

Python

# Python code to print largest permutation after K swaps
 
def KswapPermutation(arr, n, k):
 
    # Auxiliary array of storing the position of elements
    pos = {}
    for i in range(n):
        pos[arr[i]] = i
 
    for i in range(n):
 
        # If K is exhausted then break the loop
        if k == 0:
            break
 
        # If element is already largest then no need to swap
        if (arr[i] == n-i):
            continue
 
        # Find position of i'th largest value, n-i
        temp = pos[n-i]
 
        # Swap the elements position
        pos[arr[i]] = pos[n-i]
        pos[n-i] = i
 
        # Swap the ith largest value with the value at
        # ith place
        arr[temp], arr[i] = arr[i], arr[temp]
 
        # Decrement K after swap
        k = k-1
 
# Driver code
arr = [4, 5, 2, 1, 3]
n = len(arr)
k = 3
KswapPermutation(arr, N, K)
 
# Print the answer
print "Largest permutation after", K, "swaps: "
print " ".join(map(str, arr))

C#

// Below is C# code to print largest
// permutation after atmost K swaps.
using System;
 
class GFG {
 
    // Function to calculate largest
    // permutation after atmost K
    // swaps
    static void KswapPermutation(int[] arr,
                                 int n, int k)
    {
 
        // Auxiliary dictionary of storing
        // the position of elements
        int[] pos = new int[n + 1];
 
        for (int i = 0; i < n; ++i)
            pos[arr[i]] = i;
 
        for (int i = 0; i < n && k > 0; ++i) {
 
            // If element is already i'th
            // largest, then no need to swap
            if (arr[i] == n - i)
                continue;
 
            // Find position of i'th largest
            // value, n-i
            int temp = pos[n - i];
 
            // Swap the elements position
            pos[arr[i]] = pos[n - i];
            pos[n - i] = i;
 
            // Swap the ith largest value with
            // the current value at ith place
            int tmp1 = arr[temp];
            arr[temp] = arr[i];
            arr[i] = tmp1;
 
            // decrement number of swaps
            --k;
        }
    }
 
    // Driver method
    public static void Main()
    {
 
        int[] arr = { 4, 5, 2, 1, 3 };
        int n = arr.Length;
        int k = 3;
 
        KswapPermutation(arr, n, k);
 
        Console.Write("Largest permutation "
                      + "after " + k + " swaps:\n");
 
        for (int i = 0; i < n; ++i)
            Console.Write(arr[i] + " ");
    }
}
 
// This code is contributed nitin mittal.

PHP


Javascript


输出:

Largest permutation after 3 swaps:
5 4 3 2 1

实现 2:这使用哈希图来获得解决方案。

C++

// C++ Program to find the
// largest permutation after
// at most k swaps using unordered_map.
#include 
#include 
using namespace std;
 
// Function to find the largest
// permutation after k swaps
void bestpermutation(
    int arr[], int k, int n)
{
    // Storing the elements and
    // their index in map
    unordered_map h;
    for (int i = 0; i < n; i++) {
        h.insert(make_pair(arr[i], i));
    }
 
    // If number of swaps allowed
    // are equal to number of elements
    // then the resulting permutation
    // will be descending order of
    // given permutation.
    if (n <= k) {
        sort(arr, arr + n, greater());
    }
    else {
 
        for (int j = n; j >= 1; j--) {
            if (k > 0) {
 
                int initial_index = h[j];
                int best_index = n - j;
 
                // if j is not at it's best index
                if (initial_index != best_index) {
 
                    h[j] = best_index;
 
                    // Change the index of the element
                    // which was at position 0. Swap
                    // the element basically.
                    int element = arr[best_index];
                    h[element] = initial_index;
                    swap(
                        arr[best_index],
                        arr[initial_index]);
 
                    // decrement number of swaps
                    k--;
                }
            }
        }
    }
}
 
// Driver code
int main()
{
    int arr[] = { 3, 1, 4, 2, 5 };
 
    // K is the number of swaps
    int k = 10;
 
    // n is the size of the array
    int n = sizeof(arr) / sizeof(int);
 
    // Function calling
    bestpermutation(arr, k, n);
 
    cout << "Largest possible permutation after "
         << k << " swaps is ";
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
 
    return 0;
}
// This method is contributed by Kishan Mishra.

Java

// Java Program to find the
// largest permutation after
// at most k swaps using unordered_map.
import java.util.*;
class GFG
{
 
  // Function to find the largest
  // permutation after k swaps
  static void bestpermutation(ArrayList arr, int k, int n)
  {
 
    // Storing the elements and
    // their index in map
    HashMap h =  
      new HashMap(); 
    for (int i = 0; i < n; i++)
    {
      h.put(arr.get(i), i);
    }
 
    // If number of swaps allowed
    // are equal to number of elements
    // then the resulting permutation
    // will be descending order of
    // given permutation.
    if (n <= k) {
      Collections.sort(arr, Collections.reverseOrder()); 
    }
    else {
 
      for (int j = n; j >= 1; j--)
      {
        if (k > 0)
        {
 
          int initial_index = h.get(j);
          int best_index = n - j;
 
          // if j is not at it's best index
          if (initial_index != best_index)
          {
            h.put(j, best_index);
 
            // Change the index of the element
            // which was at position 0. Swap
            // the element basically.
            int element = arr.get(best_index);
            h.put(element, initial_index);
            int temp = arr.get(best_index);
            arr.set(best_index, arr.get(initial_index));
            arr.set(initial_index, temp);
 
            // decrement number of swaps
            k--;
          }
        }
      }
    }
  }
 
  // Driver code
  public static void main(String []args)
  {
 
    ArrayList arr = new ArrayList();
    arr.add(3);
    arr.add(1);
    arr.add(4);
    arr.add(2);
    arr.add(5);
 
    // K is the number of swaps
    int k = 10;
 
    // n is the size of the array
    int n = arr.size();
 
    // Function calling
    bestpermutation(arr, k, n);
 
    System.out.print("Largest possible permutation after " + k + " swaps is ");
 
    for (int i = 0; i < n; i++)
      System.out.print(arr.get(i) + " ");
  }
}
 
// This code is contributed by rutvik_56.

蟒蛇3

# Python3 program to find the
# largest permutation after
# at most k swaps using unordered_map.
 
# Function to find the largest
# permutation after k swaps
def bestpermutation(arr, k, n):
     
    # Storing the elements and
    # their index in map
    h = {}
    for i in range(n):
        h[arr[i]] = i
 
    # If number of swaps allowed
    # are equal to number of elements
    # then the resulting permutation
    # will be descending order of
    # given permutation.
    if (n <= k):
        arr.sort()
        arr.reverse()
    else:
         
        for j in range(n, 0, -1):
            if (k > 0):
                initial_index = h[j]
                best_index = n - j
 
                # If j is not at it's best index
                if (initial_index != best_index):
                    h[j] = best_index
 
                    # Change the index of the element
                    # which was at position 0. Swap
                    # the element basically.
                    element = arr[best_index]
                    h[element] = initial_index
                    arr[best_index], arr[initial_index] = (arr[initial_index],
                                                           arr[best_index])
                                                            
                    # Decrement number of swaps
                    k -= 1
 
# Driver Code
arr = [ 3, 1, 4, 2, 5 ]
 
# K is the number of swaps
k = 10
 
# n is the size of the array
n = len(arr)
 
# Function calling
bestpermutation(arr, k, n)
 
print("Largest possible permutation after",
      k, "swaps is", end = " ")
       
for i in range(n):
    print(arr[i], end = " ")
 
# This code is contributed by divyesh072019

C#

// C# Program to find the
// largest permutation after
// at most k swaps using unordered_map.
using System;
using System.Collections.Generic;
class GFG {
     
    // Function to find the largest
    // permutation after k swaps
    static void bestpermutation(List arr, int k, int n)
    {
        // Storing the elements and
        // their index in map
        Dictionary h =  
                       new Dictionary(); 
        for (int i = 0; i < n; i++) {
            h.Add(arr[i], i);
        }
      
        // If number of swaps allowed
        // are equal to number of elements
        // then the resulting permutation
        // will be descending order of
        // given permutation.
        if (n <= k) {
            arr.Sort();
            arr.Reverse();
        }
        else {
      
            for (int j = n; j >= 1; j--) {
                if (k > 0) {
      
                    int initial_index = h[j];
                    int best_index = n - j;
      
                    // if j is not at it's best index
                    if (initial_index != best_index) {
      
                        h[j] = best_index;
      
                        // Change the index of the element
                        // which was at position 0. Swap
                        // the element basically.
                        int element = arr[best_index];
                        h[element] = initial_index;
                        int temp = arr[best_index];
                        arr[best_index] = arr[initial_index];
                        arr[initial_index] = temp;
      
                        // decrement number of swaps
                        k--;
                    }
                }
            }
        }
    }
 
  static void Main() {
    List arr = new List(new int[] {3, 1, 4, 2, 5 });
  
    // K is the number of swaps
    int k = 10;
  
    // n is the size of the array
    int n = arr.Count;
  
    // Function calling
    bestpermutation(arr, k, n);
  
    Console.Write("Largest possible permutation after " + k + " swaps is ");
    for (int i = 0; i < n; i++)
        Console.Write(arr[i] + " ");
  }
}
 
// This code is contributed by divyeshrabadiya07

Javascript


输出:

Largest possible permutation after 10 swaps is 5 4 3 2 1

复杂度分析:

  • 时间复杂度: O(N)。
    只需要遍历一次数组。
  • 空间复杂度: O(n)。
    存储新数组需要 O(n) 空间。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程