# Maximum Swap

You are given an integer `num`

. You can swap two digits at most once to get the maximum valued number.Return *the maximum valued number you can get*.

**Example 1:**

**Input:** num = 2736

**Output:** 7236

**Explanation:** Swap the number 2 and the number 7.

**Example 2:**

**Input:** num = 9973

**Output:** 9973

**Explanation:** No swap.

**Constraints:**

`0 <= num <= 108`

Solution : This problem has few algorithmic steps.

- Convert the numbers into an integer array so that we can perform swapping.
- 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.
- If maxInSubSet is greater than max value then we have to swap the value present at maxInSubset position with max position.
- As we allowed to do only one swap so once one swap is done , we will exit the loop.
- There is edge case here , if both max and maxInsubset will be equal then we will not perform any swap.

Time Complexity : As it is brute force approach so it has big o(n*2) time complexity.

Space Complexity : O(n) → As we are using extra space to store the number in a list and array.

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);

}

}