Skip to content

Commit 16da767

Browse files
solves #2566: Maximum Difference by Remapping a Digit in java
1 parent c9e3b26 commit 16da767

File tree

2 files changed

+38
-1
lines changed

2 files changed

+38
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -801,7 +801,7 @@
801801
| 2553 | [Separate the Digits in an Array](https://leetcode.com/problems/separate-the-digits-in-an-array) | [![Java](assets/java.png)](src/SeparateTheDigitsInAnArray.java) | |
802802
| 2558 | [Take Gifts From the Richest Pile](https://leetcode.com/problems/take-gifts-from-the-richest-pile) | [![Java](assets/java.png)](src/TakeGiftsFromTheRichestPile.java) | |
803803
| 2562 | [Find the Array Concatenation Value](https://leetcode.com/problems/find-the-array-concatenation-value) | [![Java](assets/java.png)](src/FindTheArrayConcatenationValue.java) | |
804-
| 2566 | [Maximum Difference by Remapping a Digit](https://leetcode.com/problems/maximum-difference-by-remapping-a-digit) | | |
804+
| 2566 | [Maximum Difference by Remapping a Digit](https://leetcode.com/problems/maximum-difference-by-remapping-a-digit) | [![Java](assets/java.png)](src/MaximumDifferenceByRemappingADigit.java) | |
805805
| 2570 | [Merge Two 2D Arrays by Summing Values](https://leetcode.com/problems/merge-two-2d-arrays-by-summing-values) | | |
806806
| 2574 | [Left and Right Sum Differences](https://leetcode.com/problems/left-and-right-sum-differences) | | |
807807
| 2578 | [Split With Minimum Sum](https://leetcode.com/problems/split-with-minimum-sum) | | |

Diff for: src/MaximumDifferenceByRemappingADigit.java

+37
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// https://leetcode.com/problems/maximum-difference-by-remapping-a-digit
2+
// T: O(log(N))
3+
// S: O(1)
4+
5+
public class MaximumDifferenceByRemappingADigit {
6+
public int minMaxDifference(int num) {
7+
final String number = num + "";
8+
final int maxDigit = maxDigit(number);
9+
final int minDigit = minDigit(number);
10+
return maxDigit - minDigit;
11+
}
12+
13+
private int maxDigit(String x) {
14+
for (int i = 0 ; i < x.length() ; i++) {
15+
int digit = x.charAt(i) - '0';
16+
if (digit < 9) {
17+
return changeOccurrence(x, digit, 9);
18+
}
19+
}
20+
return Integer.parseInt(x);
21+
}
22+
23+
private int minDigit(String x) {
24+
for (int i = 0 ; i < x.length() ; i++) {
25+
int digit = x.charAt(i) - '0';
26+
if (digit != 0) {
27+
return changeOccurrence(x, digit, 0);
28+
}
29+
}
30+
return Integer.parseInt(x);
31+
}
32+
33+
private int changeOccurrence(String x, int digit, int to) {
34+
final String result = x.replace((char) (digit + '0'), (char) (to + '0'));
35+
return Integer.parseInt(result);
36+
}
37+
}

0 commit comments

Comments
 (0)