1
+ """
2
+ You are given a positive integer num. You may swap any two digits of num that have the same parity (i.e. both odd digits or both even digits).
3
+
4
+ Return the largest possible value of num after any number of swaps.
5
+
6
+
7
+
8
+ Example 1:
9
+
10
+ Input: num = 1234
11
+ Output: 3412
12
+ Explanation: Swap the digit 3 with the digit 1, this results in the number 3214.
13
+ Swap the digit 2 with the digit 4, this results in the number 3412.
14
+ Note that there may be other sequences of swaps but it can be shown that 3412 is the largest possible number.
15
+ Also note that we may not swap the digit 4 with the digit 1 since they are of different parities.
16
+ Example 2:
17
+
18
+ Input: num = 65875
19
+ Output: 87655
20
+ Explanation: Swap the digit 8 with the digit 6, this results in the number 85675.
21
+ Swap the first digit 5 with the digit 7, this results in the number 87655.
22
+ Note that there may be other sequences of swaps but it can be shown that 87655 is the largest possible number.
23
+
24
+
25
+ Constraints:
26
+
27
+ 1 <= num <= 109
28
+ """
29
+ class Solution :
30
+ def largestInteger (self , num : int ) -> int :
31
+ odd ,even ,odd_nums ,even_nums = set (),set (),[],[]
32
+ for i ,digit in enumerate (str (num )):
33
+ if int (digit ) % 2 == 0 :
34
+ even .add (i )
35
+ even_nums .append (int (digit ))
36
+ else :
37
+ odd .add (i )
38
+ odd_nums .append (int (digit ))
39
+ odd_nums .sort (reverse = True )
40
+ even_nums .sort (reverse = True )
41
+ result ,o ,e = [],0 ,0
42
+ for i in range (len (str (num ))):
43
+ if i in odd :
44
+ result .append (str (odd_nums [o ]))
45
+ o += 1
46
+ elif i in even :
47
+ result .append (str (even_nums [e ]))
48
+ e += 1
49
+ return int ('' .join (result ))
0 commit comments