We need to find the largest permutation after at most K swaps. This is a classic problem: given a permutation of numbers from 1 to N? Wait, the problem statement says "N natural numbers", not necessarily a permutation of 1..N? Typically in "largest permutation" problems, the numbers are distinct and maybe from 1 to N. But sample: 4 2 3 5 1: these are distinct and are 1..5 but not sorted. So it's a permutation of numbers 1..N? It says natural numbers. Possibly distinct, but not necessarily? Usually in such problems it's a permutation of first N natural numbers? But let's read problem: "You are given N natural numbers and K swaps are allowed. Determine the largest permutation that you can attain." The sample: N=5, K=1, arr = [4,2,3,5,1], output [5,2,3,4,1]. That's typical: we can swap at most K times, each swap swaps any two positions? Usually we can swap any two elements. So we want the lexicographically largest permutation possible with at most K swaps. Classic solution: we want the array to be sorted in descending order as much as possible given limited swaps. So we start from leftmost index, and for each position i, we want the largest remaining number to be placed there, but we have a limited number of swaps. Typically we swap the element at i with the maximum in the suffix (from i to end) if that maximum is greater than the current element, and the cost (distance? Actually swap count just increments by 1 regardless of distance? Usually swapping any two positions counts as one swap. So we can directly swap elements anywhere. So we can perform up to K swaps, each swap exchanges two positions. So we can choose any pair each time. To get largest lexicographic permutation, we want the first element as large as possible, then second, etc. So we can do: for i from 1 to N, if K>0, find the maximum element from i to N; if that maximum is greater than arr[i], swap it with arr[i] (i.e., bring it to front) and decrement K. This yields the largest permutation possible with at most K swaps. That's a known algorithm. The sample: i=0 (1-indexed? Let's do 0-index). arr = [4,2,3,5,1]. i=0: max from i..4 is 5 at index 3, >4 => swap arr[0] and arr[3] => [5,2,3,4,1], K=0, stop. Output matches.
But what if numbers are not necessarily 1..N? The algorithm works for any distinct numbers. If there are duplicates, we need to be careful: we want lexicographically largest array. The algorithm of swapping the maximum in suffix if greater than current works. If there are multiple occurrences of maximum, we should pick the rightmost? Actually if there is tie, swapping with the leftmost occurrence in the suffix might be fine, but if we swap with the leftmost, we might later need to swap something else. Actually standard approach: for each i, find the largest element in suffix. If there are multiple, we could swap with the one that yields the least "damage"? Usually we want to minimize the number of swaps: if the current element is already the max, we don't swap. If not, we swap with the max. But if the max appears multiple times, swapping with the rightmost might help preserve later order? But since we only care about lexicographic order, after placing the max at position i, the rest can be dealt later. But if we swap with the rightmost occurrence, we might be able to bring a slightly smaller element to position i and keep a max for later? Actually no: if we bring the max to position i, we need to swap it with the element currently at i. The element we place at i becomes the max, so that's best. The element we put back into the suffix (the original arr[i]) goes to the position of the max. That could affect later positions. But since we only have K swaps total, we need to ensure that each swap is used optimally. However, typical greedy algorithm works: for each i, find the maximum in the suffix. If it's greater than arr[i], swap it with arr[i] and decrement K. This yields the optimal lexicographically largest array when swaps are unlimited? Actually if swaps unlimited, you'd sort descending. With limited K, greedy works: always swap the current position with the largest element in the remaining suffix, if it's larger. This yields the lexicographically largest possible after at most K swaps. Proof: Lexicographic order is determined by earliest differences. To maximize, we want the first element as large as possible, subject to the constraint of at most K swaps. If we can bring the maximum element to first position using at most 1 swap (if it's not already there), we should because any alternative that leaves a smaller element at first cannot be lexicographically larger, regardless of later positions. So we allocate a swap to bring max to first if needed. But we must consider that bringing max to first might cost more than 1 swap if the max is not directly accessible? But we can swap any two positions, so we can bring max from any position j to position i in one swap. So it always costs 1 swap to place the max at i if it's not already there. So it's straightforward. However, we need to ensure that we don't waste swaps: if we have K swaps, we can at most do K such improvements. The greedy algorithm picks the leftmost positions where a swap yields improvement, each using 1 swap. This is optimal.
Thus solution: For i = 0 to N-1, if K > 0:
- Find the maximum element in arr[i...N-1].
- If that max > arr[i], swap arr[i] with the element equal to max (choose the first occurrence? Actually any occurrence works, but we might want to pick the rightmost occurrence to avoid swapping again? Let's think: Suppose we have duplicate max values. If we swap with the leftmost max in suffix, then later at that leftmost position (now contains arr[i]) we might again want to swap that element if it is not the max for that later position. But we have limited K, and we don't want to waste swaps. However, if there are duplicates, the maximum value is same. Swapping with any occurrence yields same arr[i] = max. The element placed at the position of max could be smaller. But later when we get to that index, we may consider swapping it again if we have remaining swaps. But that would be suboptimal because we already used a swap to bring the max to i; maybe we could have chosen a different occurrence to minimize the need for further swaps? For example, arr = [1, 3, 2, 3], K=1. Greedy: i=0, max in suffix is 3 (positions 1 and 3). If we swap with position 1, we get [3,1,2,3]. That's the largest with one swap? If we swap with position 3, we get [3,3,2,1]? Wait, swapping with position 3: arr[0] (1) <-> arr[3] (3) gives [3,3,2,1]? Actually original: [1,3,2,3]; swap indices 0 and 3 gives [3,3,2,1]. That's lexicographically larger than [3,1,2,3] because at index 1: 3 vs 1, 3 > 1. So clearly swapping with the rightmost max yields better result. So we should choose the rightmost occurrence of the maximum in the suffix. Reason: By swapping with the rightmost max, we put the original arr[i] (which is smaller) as far right as possible, minimizing its impact on lexicographic order for future positions. Also, if there are duplicates, swapping with the rightmost might avoid needing to swap later. So standard solution: For each i, if K>0, find the maximum element in suffix, and also the rightmost index where that max occurs. Then if that max > arr[i], swap arr[i] with arr[maxIndex]. This reduces K by 1. After finishing, output arr.
Now, constraints: N up to 1e5, K up to 1e5. Doing O(N^2) search for each i is too slow. Need O(N log N) or O(N) with some data structure. Typical approach: Precompute the maximum suffix or use a data structure like a segment tree to query maximum and its rightmost index in a range quickly. Since we only need to do at most K swaps, and K up to 1e5, but N also up to 1e5. In worst case K = N, so we could do up to N iterations. So we need O(N log N) or O(N) if we use a precomputed array? Let's think.
We can process i from 0 to N-1. For each i, we need the maximum element in suffix i..N-1. But after we swap, the array changes; we need to update data structure. So we need a dynamic data structure supporting range maximum query and update (swap two positions). Segment tree or Fenwick tree? But we need to find rightmost index of the maximum. So a segment tree that stores (value, rightmost index) or (max, maxIndex) where maxIndex is the rightmost occurrence of the maximum in that segment. For a node covering [l,r], we can compute: if left.max > right.max, then node.max = left.max, node.maxIndex = left.maxIndex; else if right.max > left.max, then node.max = right.max, node.maxIndex = right.maxIndex; else (equal), node.max = left.max (=right.max), node.maxIndex = right.maxIndex (since we want rightmost). So we can build segment tree in O(N). Then for each i, we query over [i, N-1] to get (maxVal, maxIndex). If maxVal > arr[i], we swap arr[i] and arr[maxIndex]. After swapping, we need to update two positions in segment tree: set position i to new value (maxVal) and position maxIndex to old arr[i]. That's two point updates. Query each iteration O(log N). So total O(N log N) or O(K log N) whichever smaller, but overall O(N log N). Since N <= 1e5, it's fine.
Alternatively, we can use a simpler approach: Since numbers are from 1..N maybe, we can precompute the desired descending order and then greedily swap. If numbers are a permutation of 1..N, we can keep an array of positions of values (value->index). Then we can iterate i from 0 and desired value = N-i (largest). We check if arr[i] != desired and K>0, then we swap arr[i] with the element that has value desired. But careful: after swap, we need to update position mapping. This yields O(N) time if we have position mapping. However, the problem says "natural numbers", not necessarily 1..N. But sample suggests distinct? Usually they are distinct. Even if not, we can use segment tree for generic numbers. But many online judges have this problem: "Largest Permutation" where numbers are 1..N. Actually I've seen a problem: "Largest Permutation" from Hackerrank: given N and K, and a permutation of numbers 1..N, find the largest permutation after at most K swaps. Solution: use position array and iterate. So likely it's that problem. Constraints N up to 1e5, K up to 1e5.
But the problem statement here: "You are given N natural numbers" doesn't explicitly say they are a permutation of 1..N, but sample uses 1..5. Could be typical. To be safe, we should handle generic distinct numbers? The problem statement says "N natural numbers". They could be any natural numbers (positive integers) possibly with duplicates? However, the largest permutation would then be ambiguous if duplicates exist: swapping duplicates doesn't change. So we can assume distinct maybe. But to be safe, we can implement a solution that works for distinct numbers (and if duplicates exist, we should choose rightmost max). But position mapping approach requires values to be unique to map value->index. If duplicates exist, there would be multiple indices for a given value, and swapping decisions become more nuanced (choose rightmost). The position mapping approach fails for duplicates. However, typical competitive programming problem states "N natural numbers" meaning a permutation of 1..N (as in "The first N natural numbers"). Actually "N natural numbers" could be ambiguous. In many problems: "given an array of N integers" but here they say "natural numbers". Possibly they intend 1..N. Also the sample: 4 2 3 5 1 contains each from 1 to 5 exactly once. So I'm leaning that it's a permutation of 1..N.
But let's double-check: The problem says "largest permutation". This implies the array is a permutation. So yes.
Thus simpler solution: Use an array pos where pos[value] = current index of that value. We want to create the largest lexicographic permutation, which is descending order of numbers (since numbers are 1..N). So we iterate i from 0 to N-1. The largest possible value we'd like at position i is N-i (since descending). But we may not achieve exactly descending because of limited K. So we start with i=0, desired = N. If arr[i] is not desired and K>0, we need to swap arr[i] with the element that currently holds desired. Let j = pos[desired]. Then swap arr[i] and arr[j]. Update pos[arr[i]] to j (since arr[i] moves to j) and pos[desired] to i. Decrement K. Then move to i+1, desired = N-1, etc. But careful: after swapping, arr[i] becomes desired, which is fine. But we also need to update pos for the swapped value (original arr[i]) accordingly. This algorithm is O(N) and is simple.
However, there is a nuance: In some cases, we might have arr[i] already equal to desired, no swap needed. If arr[i] != desired, we swap. But what if arr[i] is not desired but the desired element is already in a position that is less than i? Actually desired = N-i; since we process left to right, the desired values are the largest ones we haven't placed yet. At step i, we intend to place the largest remaining number. The largest remaining number is N-i if we haven't placed it yet. But if we placed a larger number earlier (by swapping), the next largest is N-i-1? Actually at step i, after previous steps, the numbers placed at indices 0..i-1 are the largest i numbers (N, N-1, ..., N-i+1) in order. So the remaining numbers are from 1 to N-i. So the largest remaining is N-i. So yes.
Now, consider if the desired element is already at a position < i? That cannot happen because those positions already contain larger numbers. Actually desired (N-i) is not larger than numbers already placed; it is smaller. So it cannot be in earlier positions because earlier positions hold numbers > N-i. So it must be in some position >= i. So pos[desired] >= i. Good.
So algorithm stands.
Edge cases: K > N? We can only swap at most N-1 times to get descending order. So we can cap K to N effectively. Actually we can stop when i reaches N or K=0.
Now, for output: print the array after performing swaps.
Let's test with sample: N=5, K=1. arr = [4,2,3,5,1]. pos: value->index: pos[4]=0, pos[2]=1, pos[3]=2, pos[5]=3, pos[1]=4. i=0, desired=5, arr[0]=4 !=5, K=1>0, swap arr[0] with arr[pos[5]=3]. Swap: arr becomes [5,2,3,4,1]. Update pos[5]=0, pos[4]=3. K=0. Next i=1, desired=4? But K=0 so no more swaps. The final arr = [5,2,3,4,1] matches.
Test with duplicate? Not needed.
Another test: N=5, K=2, arr = [4,2,3,5,1]. i=0: swap 4 and 5 -> [5,2,3,4,1], K=1, pos[5]=0, pos[4]=3. i=1: desired=4, arr[1]=2 !=4, K>0, pos[4]=3, swap arr[1] and arr[3] -> [5,4,3,2,1], K=0. Output [5,4,3,2,1] which is sorted descending.
Test with K=1 but arr already descending: [5,4,3,2,1], i=0: arr[0]=5=desired, no swap; i=1: 4=4, no swap, etc. Output same.
Test where K is large but arr is almost descending: works.
Now, if numbers are not necessarily 1..N but distinct and any natural numbers, the position map approach would need to know what values to desire. We could sort the array descending to get the order of desired values. Then for each i, desired = sorted[i] (the i-th largest). Then if arr[i] != desired and K>0, swap arr[i] with the element that equals desired. But we need to know the index of desired. Since values are distinct, we can create a map from value to index. However, after swaps, we need to update the map for the two swapped values. Complexity O(N log N) due to sorting, but overall O(N) if we use hash map (unordered_map) and sorting O(N log N). That's acceptable. But we must be careful: If duplicates exist, the desired value may appear multiple times; we need to decide which index to swap. For duplicates, the largest permutation concept might be more subtle, but often inputs are distinct. The problem likely expects distinct numbers, and indeed it's called a permutation. So we can assume distinct.
Given constraints, I'll implement the position map solution assuming values are 1..N. But to be safe, I could implement the generic sorted approach, but it's straightforward. However, if the values are not 1..N but still distinct and we want largest lexicographic permutation, the greedy algorithm remains: for each i from 0, desired is the i-th largest among remaining numbers? Actually we want lexicographically largest, so we want to place the largest possible number at position 0, then next largest at position 1, etc. So the optimal arrangement if we had unlimited swaps would be the array sorted in descending order. With limited swaps, we can greedily swap the current position with the largest remaining number if it's not already there. This is exactly the same as before, but we need to know what is the largest remaining number. But we don't need to precompute the sorted order; we can use a data structure like a max-heap of remaining numbers with indices? But we need to handle swaps and updates. Simpler: we can do the segment tree approach which is generic and handles duplicates appropriately. However, for efficiency, the position map with desired values = N-i works only when numbers are 1..N. Since the problem statement says "natural numbers", and sample uses 1..5, I think it's safe to assume they are 1..N. Many online problems are like "You are given an array of the first N natural numbers" i.e., a permutation of 1..N. So I'll go with that.
But to confirm, check the problem statement: "You are given N natural numbers" might be interpreted as "You are given N natural numbers (the first N natural numbers?)". It's ambiguous, but I'm leaning that it's a permutation of 1..N. Let's see if any edge case: N could be up to 1e5, so values could be up to? If they are any natural numbers, they could be larger than N, but then the descending order wouldn't be simply N, N-1, etc. So the problem's typical name is "Largest Permutation" and it's from sources where it's a permutation of 1..N. I'll adopt that.
Thus solution steps:
- Read N, K.
- Read array arr of size N.
- Create vector pos of size N+1 (since values 1..N). Initialize: for i in 0..N-1, pos[arr[i]] = i.
- For i from 0 to N-1:
a. desired = N - i.
b. If K == 0: break.
c. If arr[i] != desired:
j = pos[desired] // index where desired is currently
// swap arr[i] and arr[j]
swap(arr[i], arr[j])
// update positions: the value that was at i (arr[i] after swap? careful)
// Actually after swap, we need to update pos for the two values:
// Original arr[i] is some value, say cur = arr[i] before swap.
// But we can update after swapping:
// Let cur_i = arr[i] before swap, cur_j = desired.
// After swap: arr[i] becomes desired, arr[j] becomes cur_i.
// So update pos[desired] = i; pos[cur_i] = j.
// We need cur_i before swapping. So store cur_i = arr[i] before swap.
// Implementation:
// int cur = arr[i];
// swap(arr[i], arr[j]);
// pos[desired] = i;
// pos[cur] = j;
// K--.
- Output arr.
One nuance: When arr[i] == desired, we do nothing.
Time complexity O(N). Works for N up to 1e5.
But consider scenario where desired element is already at position i, but there are other elements larger? Actually desired is the maximum remaining, so it's the largest. So if arr[i] is already that largest, fine.
Edge Cases: K could be > N, but we will stop after N iterations because after we placed all numbers, no more swaps needed. In worst case we may do up to N swaps (if arr is ascending). But K may be larger than N; we simply stop when we have placed all numbers in descending order. So break when i == N or K == 0. So it's fine.
Now, confirm with another test: N=3, K=1, arr = [1,2,3]. Process:
i=0, desired=3, arr[0]=1 !=3, swap with pos[3]=2 -> arr becomes [3,2,1], update pos[3]=0, pos[1]=2, K=0. Output [3,2,1] which is largest with one swap (swap first and last). Good.
If K=2, same arr: after i=0 swap K=1, arr=[3,2,1]; i=1 desired=2, arr[1]=2 already, no swap; i=2 desired=1, arr[2]=1, no swap. Output [3,2,1]. That's descending, done. That's correct.
If K=2 and arr = [3,1,2] (descending? Actually not descending). i=0 desired=3, arr[0]=3 already; K remains 2; i=1 desired=2, arr[1]=1 !=2, swap with pos[2]=2 => arr becomes [3,2,1], K=1; i=2 desired=1, arr[2]=1 already. Output [3,2,1]. Good.
Now, duplicate case is not considered.
Thus solution is straightforward.
Now, think about possible pitfalls: The array values might not be exactly 1..N? If some numbers are missing or repeated, pos array might have uninitialized entries or collisions. But given problem is permutation, it's safe. However, to be robust, we can allocate a map for generic numbers: but that might be slower but acceptable. But I'll go with pos array of size N+1 because values are 1..N.
Now, let's implement in C++.
Plan:
#include
#include
using namespace std;
int main() {
int N, K;
cin >> N >> K;
vector arr(N);
vector pos(N+1); // positions of numbers 1..N
for (int i = 0; i < N; ++i) {
cin >> arr[i];
pos[arr[i]] = i;
}
for (int i = 0; i < N && K > 0; ++i) {
int desired = N - i;
if (arr[i] != desired) {
int j = pos[desired];
// swap arr[i] and arr[j]
int cur = arr[i];
arr[i] = desired;
arr[j] = cur;
// update positions
pos[desired] = i;
pos[cur] = j;
--K;
}
}
// output
for (int i = 0; i < N; ++i) {
cout << arr[i];
if (i != N-1) cout << " ";
}
cout << endl;
return 0;
}
That's it.
But wait: Is it always optimal to use the desired as N-i? For permutation of 1..N, yes. But what if values are not 1..N? Example: arr = [10, 20, 30], N=3, K=1. Desired largest is 30, then 20, then 10. So desired sequence descending. Our algorithm would need to know that. If we assume 1..N, it fails. But problem says "natural numbers", which could be any positive integer, maybe not necessarily 1..N. However, typical problem statement "N natural numbers" might be ambiguous. I recall a problem on HackerRank: "Largest Permutation" where the array contains numbers 1 to N. The input description says: "The first line contains two integers, N and K. The second line contains N space separated integers, denoting the elements of the array." It doesn't explicitly say it's a permutation, but the problem context is permutation. So it's probably that.
To be safe, we could note that the algorithm for generic distinct numbers can be implemented using a sorted list and map. But given the constraints and typical problem, I'll provide solution with pos array of size N+1.
But for the purpose of ChatGPT answering, we should provide explanation and code. Since the user expects an answer, we can present the solution with the assumption that numbers are from 1 to N.
Nevertheless, the problem statement as given: "You are given N natural numbers" doesn't guarantee they are 1..N. Could be any N natural numbers, e.g., 5, 100, 2, etc. In that case, the largest permutation would be descending order of those numbers. The greedy algorithm still works: for i from 0, find the largest number in suffix and swap if larger than current. That's the generic solution. So I'd like to implement a robust solution that works for any distinct numbers (or with duplicates). But given N up to 1e5, we can implement segment tree as described. However, implementing a segment tree might be more complex. Another simpler method: we can use a "sorted list of remaining elements" but need to handle updates quickly. Could we use a heap with lazy deletion? Maybe but we need to locate the index of the max element in the suffix, not just the max value. After we move elements, the heap would need to be updated. We could maintain a set of pairs (value, index) for the suffix? But as we progress i, we consider suffix from i to end. We could start with a sorted structure (e.g., a balanced BST) containing all elements with their indices, and as we move i forward, we remove the element at i from the structure? Actually we need to query the maximum in suffix [i..N-1] quickly and also get its index. We can maintain a segment tree or a Fenwick tree for max with index. Another approach: precompute the maximum from each position to end? But after swaps, values change, so that doesn't work.
Simpler: Since we only need at most K swaps and K <= 1e5, we could do an O(N^2) in worst-case if K = N? N=1e5, O(N^2) is too big. So we need O(N log N).
Segment tree is reliable.
But maybe we can still use position mapping if we sort the array to get desired descending order. For generic distinct numbers, we can create a sorted version of the array in descending order: sorted = arr sorted descending. Then we know for each position i, the desired value is sorted[i]. Then we need to place sorted[i] at position i if possible, using swaps. This approach works if we have distinct numbers. Because we can map each value to its current index (since distinct). Then for each i from 0 to N-1, if arr[i] != sorted[i] and K>0, we swap arr[i] with the element that equals sorted[i] (i.e., index j = pos[sorted[i]]). Then update pos for the two values. This is essentially the same as the permutation of 1..N case, except the desired values are from sorted list, not N-i. So it's O(N log N) due to sorting, plus O(N) for updates. That's simpler than segment tree and handles any distinct numbers.
What about duplicates? If duplicates exist, the desired sorted order might have equal values. In lexicographic largest permutation, if duplicates exist, we would want to arrange them as descending as possible, but any arrangement of equal values yields same lexicographic order? Actually if there are duplicates, the lexicographic order depends on the order of equal values only if later positions differ. Since values are equal, swapping them doesn't change the array. So it's fine if we treat them as distinct objects but with same value. However, mapping from value to index becomes ambiguous because multiple indices have same value. The mapping would need to track one of them. If we swap, we need to be careful to pick the rightmost occurrence of the maximum to preserve lexicographic order, as earlier example shows. Using a simple value-to-index map that stores only one index (maybe the first encountered) could lead to suboptimal result if duplicates exist. But if values are distinct, it's fine. The problem says "natural numbers" but doesn't state distinctness. However, the word "permutation" in the output implies distinct? Actually the problem says "largest permutation". Usually permutation means each element appears exactly once. So we can assume distinct.
Thus using sorting and position map is safe if we assume distinct numbers. But if numbers are not necessarily distinct, the problem is ambiguous and not standard.
Thus I'll implement the simpler sorting approach with map, but also handle duplicates by ensuring that we pick the rightmost occurrence when swapping? The simple pos map with unique mapping fails for duplicates. But we can extend: For each value, we could maintain a set of indices where that value occurs, or we could treat the array as having distinct numbers because it's a permutation. I'd rather stick to the original permutation-of-1..N solution as it's the most common problem.
Given that the sample shows numbers 1..5 exactly once, I'll assume values are a permutation of 1..N.
Thus the final code is as above.
But I need to output with spaces. And reading/writing.
One more nuance: In the loop, after we swap, we continue to next i. However, what if after swapping, the new element at position i is the desired, and the element we swapped out (cur) might be larger than some later desired? That's fine.
Now, confirm with an edge case: K=0, output original array.
Now, also consider that K may be large enough to get descending order but we should stop early when we finish all positions.
Implementation details: Use 0-index. Ensure pos array size N+1 (since values 1..N). When updating pos, we must update for both values. Also note that when swapping, it's possible that j == i? But if arr[i] != desired, then desired is not at i, so j != i. So swap is fine.
One more: The desired value at each step is N - i. But after we swap, the value N-i is placed at i. Then for next i+1, desired is N-(i+1). So this works.
Now, test on a more complex case:
N=5, K=2, arr = [2,1,3,5,4]. Desired order descending: 5,4,3,2,1. Process:
i=0 desired=5, arr[0]=2 !=5, j=pos[5]=3, swap arr[0] and arr[3]: arr becomes [5,1,3,2,4], pos[5]=0, pos[2]=3, K=1.
i=1 desired=4, arr[1]=1 !=4, j=pos[4]=4, swap arr[1] and arr[4]: arr becomes [5,4,3,2,1], pos[4]=1, pos[1]=4, K=0.
Output sorted descending. Works.
If K=1, same initial arr: i=0 swap -> [5,1,3,2,4] and stop. Output [5,1,3,2,4]. That is the largest possible with one swap? Could there be larger? Suppose we swap 4 to second position? Actually we could also swap 4 from last to second? But our result: first element 5 is max, so it's lexicographically largest at first position. Could we get [5,4,3,2,1] with one swap? No because to get 4 at second position, we need to bring 4 from position 4 to 1, but that would require also moving 1 to somewhere else, but we can only do one swap, and if we swap positions 1 and 4, we get [5,4,3,2,1]? Wait: original: [2,1,3,5,4]; swapping positions 1 (index1) and 4 (index4) yields [2,4,3,5,1]. That's [2,4,3,5,1] which first element 2, not as good. So swapping to get 5 at first is best. So algorithm is correct.
Thus solution accepted.
Now, we need to output as space separated numbers.
Now, let's produce final answer with explanation and code.
Given the instructions: "You are ChatGPT, a large language model trained by OpenAI..." but we need to provide the solution. So we should output code? The user asked: "You are given N natural numbers ... Determine the largest permutation ... INPUT: ... OUTPUT: ..." It's a programming problem; the user likely expects the solution code. Possibly they want the code in a specific language? Not specified, but typical would be C++ or Python. Since constraints up to 1e5, Python with O(N log N) is fine, but O(N) solution with pos array is trivial in Python as well. However, Python's input reading is slower but okay for 1e5. I'll provide Python code for simplicity? But C++ is also fine. The problem might be from a platform expecting C++ maybe. But I can provide both? Usually ChatGPT answers with explanation and then code in a common language. I'll provide Python code because it's succinct and easy to test. But ensure performance: In Python, using list and indexing, O(N) is fine.
But careful: In Python, we need to handle large input quickly: use sys.stdin.read().split().
We'll implement:
import sys
def main():
data = sys.stdin.read().split()
if not data:
return
it = iter(data)
N = int(next(it))
K = int(next(it))
arr = [int(next(it)) for _ in range(N)]
pos = [0]*(N+1) # 1-indexed values
for i, val in enumerate(arr):
pos[val] = i
for i in range(N):
if K == 0:
break
desired = N - i
if arr[i] != desired:
j = pos[desired]
# swap arr[i] and arr[j]
cur = arr[i]
arr[i] = desired
arr[j] = cur
# update positions
pos[desired] = i
pos[cur] = j
K -= 1
print(' '.join(map(str, arr)))
if name == "main":
main()
That should work.
Potential pitfalls: In Python, indices are ints, fine.
Now, does this handle the case where desired is already at i? yes.
Now, confirm with sample:
Input:
5 1
4 2 3 5 1
Output: 5 2 3 4 1
Matches.
Now, I'll produce final answer with explanation and the code.
But the user might want a textual explanation rather than code. However, typical pattern is to provide solution description and code.
Thus final answer: provide algorithm and code.
Now, I will write the answer. We can obtain the lexicographically largest permutation by repeatedly placing the largest remaining number at the leftmost possible position, using at most K swaps. Since the array is a permutation of the numbers 1..N (as implied by the sample and common problem statements), we can use an auxiliary array pos that stores the current index of each value.
We iterate from left to right. At index i, the number we would like to have there (if we had unlimited swaps) is N - i. If the current element is already this number, we do nothing. Otherwise, we swap it with the element that currently holds N - i (found via pos), update the positions of the two swapped values, and decrement K. We stop when K reaches 0 or we finish the loop.
This runs in O(N) time and O(N) extra space, well within the constraints.
Below is a Python implementation:
import sys
def main():
data = sys.stdin.read().split()
if not data:
return
it = iter(data)
N = int(next(it))
K = int(next(it))
arr = [int(next(it)) for _ in range(N)]
# position of each value (1-indexed values)
pos = [0] * (N + 1)
for i, v in enumerate(arr):
pos[v] = i
for i in range(N):
if K == 0:
break
desired = N - i
if arr[i] != desired:
j = pos[desired]
# swap values at i and j
cur = arr[i]
arr[i] = desired
arr[j] = cur
# update positions
pos[desired] = i
pos[cur] = j
K -= 1
print(' '.join(map(str, arr)))
if __name__ == "__main__":
main()