Maximum Swap

Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
Input: num = 9973
Output: 9973
Explanation: No swap.
  • 0 <= num <= 108
  1. Convert the numbers into an integer array so that we can perform swapping.
  2. Now we have to traverse the array. On first iteration , we will set the first value as a max value and find the max value from rest of the array(maxInSubset) and its corresponding position.
  3. If maxInSubSet is greater than max value then we have to swap the value present at maxInSubset position with max position.
  4. As we allowed to do only one swap so once one swap is done , we will exit the loop.
  5. There is edge case here , if both max and maxInsubset will be equal then we will not perform any swap.
public class Solution {
public int MaximumSwap(int num) {
List<int> numbers = new List<int>();
while(num != 0)
{
int rem = num % 10;
num = num/10;
numbers.Add(rem);
}
int[] number = numbers.ToArray();
Array.Reverse(number);


int maxpos = 0;
for(int i = 0; i < number.Length ; i++)
{
int max = number[i];
int maxInSubset = 0;
for( int j = i+1 ; j < number.Length; j++)
{
if(maxInSubset <= number[j])
{
maxInSubset = number[j];
maxpos = j;
}
}

if((max < maxInSubset))
{
int temp = number[i];
number[i] = number[maxpos];
number[maxpos] = temp;
break;
}
}

String result= string.Empty;
foreach(int test in number)
{
result+=test.ToString();
}
return Int32.Parse(result);
}
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store