- #1
SlurrerOfSpeech
- 141
- 11
with at most k swaps. (In other words, like the largest number formed by swapping k digits.)
Example. A=[4,2,3,5,1], k = 1 ---> [5,2,3,4,1]
I'm wondering why my algorithm is failing the test cases which I'm unable to see.
Example. A=[4,2,3,5,1], k = 1 ---> [5,2,3,4,1]
I'm wondering why my algorithm is failing the test cases which I'm unable to see.
Code:
using System;
using System.Collections.Generic;
using System.IO;
class Solution
{
public static void Swap(int[] A, int i1, int i2)
{
int temp = A[i1];
A[i1] = A[i2];
A[i2] = temp;
}
static void Main(String[] args)
{
int[] parameters = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
int n = parameters[0];
int k = parameters[1];
int[] arr = Array.ConvertAll(Console.ReadLine().Split(' '), Int32.Parse);
for(int i = 0; i < arr.Length && k > 0; ++i)
{
if(arr[i] == n)
continue;
int j = arr.Length - 1;
for(; j > i && arr[j] != n; --j);
Swap(arr,i,j);
--n;
--k;
}
Console.WriteLine(string.Join(" ", arr));
}
}