| | | 1 | | // -------------------------------------------------------------------------------- |
| | | 2 | | // Copyright (C) 2026 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | | 3 | | // All Rights Reserved. |
| | | 4 | | // -------------------------------------------------------------------------------- |
| | | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | | 9 | | // known as Yevhenii Yeriemeieiv). |
| | | 10 | | // -------------------------------------------------------------------------------- |
| | | 11 | | |
| | | 12 | | namespace LeetCode.Algorithms.MaximumDifferenceByRemappingDigit; |
| | | 13 | | |
| | | 14 | | /// <inheritdoc /> |
| | | 15 | | public sealed class MaximumDifferenceByRemappingDigitGreedy : IMaximumDifferenceByRemappingDigit |
| | | 16 | | { |
| | | 17 | | /// <summary> |
| | | 18 | | /// Time complexity - O(log num) |
| | | 19 | | /// Space complexity - O(log num) |
| | | 20 | | /// </summary> |
| | | 21 | | /// <param name="num"></param> |
| | | 22 | | /// <returns></returns> |
| | | 23 | | public int MinMaxDifference(int num) |
| | 2 | 24 | | { |
| | 2 | 25 | | var digits = num.ToString(); |
| | | 26 | | |
| | 5 | 27 | | var targetMax = digits.FirstOrDefault(digit => digit != '9'); |
| | | 28 | | |
| | 2 | 29 | | var max = 0; |
| | | 30 | | |
| | 20 | 31 | | foreach (var digit in digits) |
| | 7 | 32 | | { |
| | 7 | 33 | | max *= 10; |
| | | 34 | | |
| | 7 | 35 | | if (digit == targetMax) |
| | 4 | 36 | | { |
| | 4 | 37 | | max += 9; |
| | 4 | 38 | | } |
| | | 39 | | else |
| | 3 | 40 | | { |
| | 3 | 41 | | max += digit - '0'; |
| | 3 | 42 | | } |
| | 7 | 43 | | } |
| | | 44 | | |
| | 2 | 45 | | var targetMin = digits[0]; |
| | | 46 | | |
| | 2 | 47 | | var min = 0; |
| | | 48 | | |
| | 20 | 49 | | foreach (var digit in digits) |
| | 7 | 50 | | { |
| | 7 | 51 | | min *= 10; |
| | | 52 | | |
| | 7 | 53 | | if (digit == targetMin) |
| | 4 | 54 | | { |
| | 4 | 55 | | min += 0; |
| | 4 | 56 | | } |
| | | 57 | | else |
| | 3 | 58 | | { |
| | 3 | 59 | | min += digit - '0'; |
| | 3 | 60 | | } |
| | 7 | 61 | | } |
| | | 62 | | |
| | 2 | 63 | | return max - min; |
| | 2 | 64 | | } |
| | | 65 | | } |