---
# System prepended metadata

title: 670. Maximum Swap
tags: [Greedy]

---

---
title: 670. Maximum Swap
tags: Greedy
description: share source code.
---

# 670. Maximum Swap

```java=
class Solution {
    public int maximumSwap(int num) {
       
        char [] digits = (num +"").toCharArray();
        int n = digits.length;
      
        char suffix [] = new char [n];
             suffix[n - 1] = digits[n - 1];
        
        for(int k = n - 2; k  >= 0; k--){
            if(suffix[k + 1] <  digits[k]){
                suffix[k] = digits[k];
            }else{
                suffix[k] = suffix[k + 1];
            }
            
        }
        
        Map<Character, Integer> map = new HashMap<>();
        for(int i = 0; i < n; i ++){
            map.put(digits[i], i);
        }
        
        for(int i = 0; i < n; i++){
            if(digits[i] < suffix[i]){
                swap(digits, i, map.get(suffix[i]));
                break;
            }
        }
      
        return Integer.parseInt(new String(digits));
    }
    
    public void swap(char [] arr, int i, int j){
         char tmp = arr[i];
         arr[i] = arr[j];
         arr[j] = tmp;
    }
}
```

