[LeetCode] 2566. Maximum Difference by Remapping a Digit
You are given an integer num. You know that Bob will sneakily remap one of the 10 possible digits (0 to 9) to another digit.
Return the difference between the maximum and minimum values Bob can make by remapping exactly one digit in num.
Notes:
When Bob remaps a digit d1 to another digit d2, Bob replaces all occurrences of d1 in num with d2.
Bob can remap a digit to itself, in which case num does not change.
Bob can remap different digits for obtaining minimum and maximum values respectively.
The resulting number after remapping can contain leading zeroes.
Example 1:
Input: num = 11891
Output: 99009
Explanation:
To achieve the maximum value, Bob can remap the digit 1 to the digit 9 to yield 99899.
To achieve the minimum value, Bob can remap the digit 1 to the digit 0, yielding 890.
The difference between these two numbers is 99009.
Example 2:
Input: num = 90
Output: 99
Explanation:
The maximum value that can be returned by the function is 99 (if 0 is replaced by 9) and the minimum value that can be returned by the function is 0 (if 9 is replaced by 0).
Thus, we return 99.
Constraints:
1 <= num <= 108
替换一个数字后的最大差值。
给你一个整数 num 。你知道 Danny Mittal 会偷偷将 0 到 9 中的一个数字 替换 成另一个数字。请你返回将 num 中 恰好一个 数字进行替换后,得到的最大值和最小值的差为多少。
注意:
当 Danny 将一个数字 d1 替换成另一个数字 d2 时,Danny 需要将 nums 中所有 d1 都替换成 d2 。
Danny 可以将一个数字替换成它自己,也就是说 num 可以不变。
Danny 可以将数字分别替换成两个不同的数字分别得到最大值和最小值。
替换后得到的数字可以包含前导 0 。
Danny Mittal 获得周赛 326 前 10 名,让我们恭喜他。
思路
这是一道字符串的实现题。给的 input 是一个字符串,表示一个数字,需要把他变成一个最大的数和一个最小的数,然后求两者的差值。首先我们思考最大的数是什么?是最高位尽量为 9,如果第一位已经为 9,那么就找到第一个不为 9 的digit,假如为 X,把所有的 X 都替换成 9。
又因为给的数字一定没有前导 0,如果最高位出现的数字为 Y,我们把所有的 Y 都替换为 0 即可。
复杂度
时间O(n) - 遍历字符串一次
空间O(1)
代码
Java实现
1 |
|