<p>You are given an integer <code>num</code>. You can swap two digits at most once to get the maximum valued number.</p>

<p>Return <em>the maximum valued number you can get</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> num = 2736
<strong>Output:</strong> 7236
<strong>Explanation:</strong> Swap the number 2 and the number 7.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> num = 9973
<strong>Output:</strong> 9973
<strong>Explanation:</strong> No swap.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>0 &lt;= num &lt;= 10<sup>8</sup></code></li>
</ul>

# class Solution:
#     def maximumSwap(self, num: int) -> int:
#         num_arr = []
#         max_num = float('-inf')
#         max_i = 0
#         num_str = str(num)
#         for i in range(len(num_str)):
#             if int(num_str[i])>max_num:
#                 max_num = int(num_str[i])
#                 max_i = max(max_i, i)
            
#             # num_arr.append(c)
#         print('max_i',max_i)
#         init_num = num_str[0]
#         print('init_num',init_num)
#         print('num_str[max_i]',num_str[max_i])
#         num_str = num_str.replace(num_str[0],num_str[max_i])
#         num_str = num_str.replace(num_str[max_i],init_num)
#         return int(num_str)

class Solution:
    def maximumSwap(self, num: int) -> int:
        num_str = list(str(num))  # Convert the number to a list of characters
        last = {int(x): i for i, x in enumerate(num_str)}  # Store the last occurrence of each digit
        print(last)
        for i, digit in enumerate(num_str):
            print(i,digit)
            for d in range(9, int(digit), -1):  # Check from 9 down to digit+1
                if last.get(d, -1) > i:  # If a larger digit occurs later
                    # Swap the current digit with the larger one
                    num_str[i], num_str[last[d]] = num_str[last[d]], num_str[i]
                    return int(''.join(num_str))  # Return the swapped number as an integer
        
        return num  # If no swap was made, return the original number

16500