Skip to content

Instantly share code, notes, and snippets.

@0001vrn
Last active July 16, 2016 12:25
Show Gist options
  • Save 0001vrn/b1efd54a6dc9cddad50ff1118849423d to your computer and use it in GitHub Desktop.
Save 0001vrn/b1efd54a6dc9cddad50ff1118849423d to your computer and use it in GitHub Desktop.
Given a number M (N-digit integer) and K-swap operations(a swap operation can swap 2 digits), devise an algorithm to get the maximum possible integer? #Google #Interview #Question
#include <iostream>
using namespace std;
/*
Approach - Selection sort descending order
*/
int Kswap(int num, int k)
{
string arr = to_string(num);
int i, j, min_idx;
int n =arr.length();
// One by one move boundary of unsorted subarray
for (i = 0; i < k; i++)
{
// Find the max element in unsorted array
min_idx = i;
for (j = i+1; j < n; j++)
if (arr[j] > arr[min_idx])
min_idx = j;
// Swap the found max element with the first element
swap(arr[min_idx], arr[i]);
}
int ans = stoi(arr);
return ans;
}
int main() {
// your code goes here
cout<<Kswap(254,2)<<endl;
cout<<Kswap(132,1)<<endl;
cout<<Kswap(132,2)<<endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment