Sponsored
Sponsored
The idea is to always try and bring the largest possible digit to the leftmost position if it maximizes the number. For this, we can use a map to record the last occurrence of each digit. By iterating through the number, we can then attempt swapping if any larger digit occurs later.
Time Complexity: O(n), where n is the number of digits in num.
Space Complexity: O(1) as the storage is constant due to limited digit size.
1using System;
2
3public class Solution {
4 public int MaximumSwap(int num) {
5 char[] digits = num.ToString().ToCharArray();
6 int[] last = new int[10];
7
8 for (int i = 0; i < digits.Length; i++) {
9 last[digits[i] - '0'] = i;
10 }
11
12 for (int i = 0; i < digits.Length; i++) {
13 for (int d = 9; d > digits[i] - '0'; d--) {
14 if (last[d] > i) {
15 char temp = digits[i];
16 digits[i] = digits[last[d]];
17 digits[last[d]] = temp;
18 return int.Parse(new string(digits));
19 }
20 }
21 }
22 return num;
23 }
24
25 public static void Main(string[] args) {
26 Solution sol = new Solution();
27 int num = 2736;
28 Console.WriteLine(sol.MaximumSwap(num));
29 }
30}
The C# implementation uses arrays and char manipulation to achieve digit swapping based on last occurrences, similar to solutions in other languages.