> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Maximum Swap Python Solution with Tests

> Tested Python solution for LeetCode 670 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 670, [Medium](/catalog/medium). Topics: [Math](/catalog/topics/math), [Greedy](/catalog/topics/greedy). [View on LeetCode](https://leetcode.com/problems/maximum-swap/description/).

Generate this problem as a practice environment: tested reference solution, 18 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 670   # by problem number
lcpy gen -s maximum_swap   # by problem name
```

## Problem

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.

### Examples

```
Input: num = 2736
Output: 7236
Explanation: Swap the number 2 and the number 7.
```

```
Input: num = 9973
Output: 9973
Explanation: No swap.
```

### Constraints

* 0 \<= num \<= 10^8

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/maximum_swap/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/maximum_swap/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(d) where d is the number of digits
    # Space: O(d)
    def maximum_swap(self, num: int) -> int:
        digits = list(str(num))
        last: dict[int, int] = {int(d): i for i, d in enumerate(digits)}
        for i, d in enumerate(digits):
            for bigger in range(9, int(d), -1):
                if bigger in last and last[bigger] > i:
                    j = last[bigger]
                    digits[i], digits[j] = digits[j], digits[i]
                    return int("".join(digits))
        return num
```

## Complexity

| Time | Space |
| - | - |
| O(d) where d is the number of digits | O(d) |

## Tags

[NeetCode All](/catalog/neetcode).


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.