|
| 1 | +/** |
| 2 | + * 1432. Max Difference You Can Get From Changing an Integer |
| 3 | + * https://leetcode.com/problems/max-difference-you-can-get-from-changing-an-integer/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an integer num. You will apply the following steps exactly two times: |
| 7 | + * - Pick a digit x (0 <= x <= 9). |
| 8 | + * - Pick another digit y (0 <= y <= 9). The digit y can be equal to x. |
| 9 | + * - Replace all the occurrences of x in the decimal representation of num by y. |
| 10 | + * - The new integer cannot have any leading zeros, also the new integer cannot be 0. |
| 11 | + * |
| 12 | + * Let a and b be the results of applying the operations to num the first and second times, |
| 13 | + * respectively. |
| 14 | + * |
| 15 | + * Return the max difference between a and b. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number} num |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var maxDiff = function(num) { |
| 23 | + const digits = num.toString().split(''); |
| 24 | + |
| 25 | + const maxNum = digits.slice(); |
| 26 | + for (let i = 0; i < maxNum.length; i++) { |
| 27 | + if (maxNum[i] !== '9') { |
| 28 | + const target = maxNum[i]; |
| 29 | + for (let j = i; j < maxNum.length; j++) { |
| 30 | + if (maxNum[j] === target) { |
| 31 | + maxNum[j] = '9'; |
| 32 | + } |
| 33 | + } |
| 34 | + break; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + const minNum = digits.slice(); |
| 39 | + if (minNum[0] !== '1') { |
| 40 | + const target = minNum[0]; |
| 41 | + for (let j = 0; j < minNum.length; j++) { |
| 42 | + if (minNum[j] === target) { |
| 43 | + minNum[j] = '1'; |
| 44 | + } |
| 45 | + } |
| 46 | + } else { |
| 47 | + for (let i = 1; i < minNum.length; i++) { |
| 48 | + if (minNum[i] !== '0' && minNum[i] !== '1') { |
| 49 | + const target = minNum[i]; |
| 50 | + for (let j = i; j < minNum.length; j++) { |
| 51 | + if (minNum[j] === target) { |
| 52 | + minNum[j] = '0'; |
| 53 | + } |
| 54 | + } |
| 55 | + break; |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return parseInt(maxNum.join('')) - parseInt(minNum.join('')); |
| 61 | +}; |
0 commit comments