← All problems

670. Maximum Swap

MediumOpen on LeetCodeProblem statement

Problem Statement

670. Maximum Swap

Medium


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.

 

Example 1:

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

Example 2:

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

 

Constraints:

Java

Source file
class Solution {
    public int maximumSwap(int num) {
        String s = String.valueOf(num);
        int n = s.length();
        char[] cs = s.toCharArray();
        for(int i=0; i<n; i++){
            for(int j = i+1; j<n; j++){
                if(cs[j]>cs[i]){
                    char temp = cs[i];
                    cs[i] = cs[j];
                    cs[j] = temp;
                    return Integer.parseInt(Stream.of(cs).map(arr -> new String(arr)).collect(Collectors.joining()));
                }
            }
        }
        return num;
    }
}