← All problems

1432. Max Difference You Can Get from Changing an Integer

MediumOpen on LeetCodeProblem statement

Problem Statement

1432. Max Difference You Can Get From Changing an Integer

Medium


You are given an integer num. You will apply the following steps to num two separate times:

Let a and b be the two results from applying the operation to num independently.

Return the max difference between a and b.

Note that neither a nor b may have any leading zeros, and must not be 0.

 

Example 1:

Input: num = 555
Output: 888
Explanation: The first time pick x = 5 and y = 9 and store the new integer in a.
The second time pick x = 5 and y = 1 and store the new integer in b.
We have now a = 999 and b = 111 and max difference = 888

Example 2:

Input: num = 9
Output: 8
Explanation: The first time pick x = 9 and y = 9 and store the new integer in a.
The second time pick x = 9 and y = 1 and store the new integer in b.
We have now a = 9 and b = 1 and max difference = 8

 

Constraints:

Java

Source file
class Solution {
    public int maxDiff(int num) {
        char[] cs = String.valueOf(num).toCharArray();
        char k = 'k', l = 'l';
        int max = 0, min = 0;
        
        for (int i = 0; i < cs.length; i++) {
            max *= 10;
            if (k == 'k' && cs[i] != '9') {
                k = cs[i];
                max += 9;
            } else if (cs[i] == k)
                max += 9;
            else
                max += cs[i] - '0';
        }
        
        if (cs[0] == '1') {
            for (int i = 0; i < cs.length; i++) {
                min *= 10;
                if (l == 'l' && cs[i] != '1' && cs[i] != '0') {
                    l = cs[i];
                    // min += 0;
                } else if (cs[i] == l)
                    ; // min += 0;
                else
                    min += cs[i] - '0';
            }
        } else {
            l = cs[0];
            for (int i = 0; i < cs.length; i++) {
                min *= 10;
                if (cs[i] == l)
                    min += 1;
                else
                    min += cs[i] - '0';
            }
        }
        // System.out.println(min + "\t" + max);
        return max - min;
    }
}