1432 - Max Difference You Can Get From Changing an Integer
정보
- 문제 보기: 1432 - Max Difference You Can Get From Changing an Integer
- 소요 시간: 17분 10초
- 풀이 언어:
java - 체감 난이도: 2️⃣
- 리뷰 횟수: ✅
풀이 키워드
스포주의
그리디
풀이 코드
정보
- 메모리: 40690 KB
- 시간: 0 ms
class Solution {
public int maxDiff(int num) {
char[] numArr = String.valueOf(num).toCharArray();
// mx: find the first none-9 digit & remap all targets to 9
int target = -1;
long mx = 0;
for (int i = 0; i < numArr.length; ++i) {
int n = numArr[i] - '0';
if (target == -1 && n != 9) target = n;
if (n == target) mx += 9;
else mx += n;
mx *= 10;
}
// mn: if the first digit is 1, find the first none-0 & none-1 digit & remap all
// else, the first digit is the taget. remap all targets to 1
target = -1;
long mn = 0;
if (numArr[0] == '1') {
mn = 10; // pre-set
for (int i = 1; i < numArr.length; ++i) {
int n = numArr[i] - '0';
if (target == -1 && n != 0 && n != 1) target = n;
if (n == target) mn += 0;
else mn += n;
mn *= 10;
}
} else {
target = numArr[0] - '0';
for (int i = 0; i < numArr.length; ++i) {
int n = numArr[i] - '0';
if (target == -1 && n != 1) target = n;
if (n == target) mn += 1;
else mn += n;
mn *= 10;
}
}
return (int)(mx/10 - mn/10);
}
}