Largest Permutation

You are given an unordered array of unique integers incrementing from 1. You can swap any two elements a limited number of times. Determine the largest lexicographical value array that can be created by executing no more than the limited number of swaps.

Example:

Input: k = 1, arr = [4,2,3,5,1]
Output: 5 2 3 4 1

Approach

C++

#include <bits/stdc++.h>
using namespace std;

vector<intlargestPermutation(int kvector<intarr)
{
    int n = arr.size();
    int tempj;
    for (int i = 0i < ni++)
    {
        if (arr[i] != n - i && k != 0)
        {
            j = i + 1;
            while (arr[j] != n - i)
            {
                j++;
            }
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            k--;
        }
    }
    return arr;
}
int main()
{

    int k = 1;
    vector<intarr = {42351};

    vector<intresult = largestPermutation(karr);

    for (int i = 0i < result.size(); i++)
    {
        cout << result[i];

        if (i != result.size() - 1)
        {
            cout << " ";
        }
    }

    return 0;
}


No comments:

Post a Comment