-
Notifications
You must be signed in to change notification settings - Fork 111
/
solution.java
71 lines (67 loc) · 2.31 KB
/
solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;
public class solution {
private static String largestPalindrome(String number, int k) {
char[] chars = number.toCharArray();
int minChange = 0;
for (int i = 0, j = chars.length - 1; i < j; i++, j--) {
if (chars[i] != chars[j]) {
minChange++;
}
}
if (minChange > k) {
return "-1";
}
int changeBoth = k - minChange;
// Iinitialize l and r by leftmost and
// rightmost ends
int i = 0;
int j = chars.length - 1;
for (; i <= j; i++, j--) {
if (chars[i] != chars[j]) {
// Replace left and right character by
// maximum of both
char maxChar = (char) Math.max(chars[i], chars[j]);
if (maxChar != '9' && changeBoth - 1 >= 0) {
/* If characters at ith or rth (one of them) is changed in the previous
loop then subtract 1 from K (1 more is
subtracted already) and make them 9 */
chars[i] = '9';
chars[j] = '9';
changeBoth--;
} else {
chars[i] = maxChar;
chars[j] = maxChar;
minChange--;
}
} else {
char maxChar = (char) Math.max(chars[i], chars[j]);
/* If none of them is changed in the
previous loop then subtract 2 from changeboth
and convert both to 9 */
if (maxChar != '9' && changeBoth - 2 >= 0) {
chars[i] = '9';
chars[j] = '9';
changeBoth -= 2;
}
}
}
if (changeBoth != 0 && i - 1 == j + 1) {
chars[i - 1] = '9';
}
String palindrome = new String(chars);
return palindrome;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int k = in.nextInt();
String number = in.next();
System.out.println(largestPalindrome(number, k));
}
}