-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution670.cs
37 lines (32 loc) · 917 Bytes
/
Solution670.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution670
{
/// <summary>
/// 670. Maximum Swap - Medium
/// <a href="https://leetcode.com/problems/maximum-swap">See the problem</a>
/// </summary>
public int MaximumSwap(int num)
{
var numStr = num.ToString();
var last = new int[10];
for (var i = 0; i < numStr.Length; i++)
{
last[numStr[i] - '0'] = i;
}
for (var i = 0; i < numStr.Length; i++)
{
for (var d = 9; d > numStr[i] - '0'; d--)
{
if (last[d] > i)
{
var swap = numStr.ToCharArray();
swap[i] = (char)(d + '0');
swap[last[d]] = numStr[i];
return int.Parse(new string(swap));
}
}
}
return num;
}
}