Skip to content

Commit 04e96cf

Browse files
committed
Added palindrome problem asked in Delta X interview
1 parent 1ae5d63 commit 04e96cf

File tree

1 file changed

+90
-0
lines changed

1 file changed

+90
-0
lines changed

java/strings/HighestPalindrome.java

+90
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
/*
2+
Asked by - Delta X
3+
4+
Make largest palindrome by changing at most K-digits
5+
Given a string containing all digits, we need to convert this string to a palindrome by changing at most K digits.
6+
If many solutions are possible then print lexicographically largest one.
7+
8+
Examples:
9+
10+
Input : str = “43435”
11+
k = 3
12+
Output : "93939"
13+
Lexicographically largest palindrome
14+
after 3 changes is "93939"
15+
16+
Input : str = “43435”
17+
k = 1
18+
Output : “53435”
19+
Lexicographically largest palindrome
20+
after 3 changes is “53435”
21+
22+
Input : str = “12345”
23+
k = 1
24+
Output : "Not Possible"
25+
It is not possible to make str palindrome
26+
after 1 change.
27+
*/
28+
29+
/*
30+
if (minChanges == k) {
31+
// if digits are different then change smaller to match larger
32+
} else if (minChanges >= k+2) {
33+
// You have spare changes. Change one or both (or neither!) to '9'
34+
} else (minChanges == k+1) {
35+
// You can make one extra change. If the digits are different, then change the smaller
36+
// to match the larger.
37+
}
38+
*/
39+
40+
class Palindrome{
41+
public static String maxPalindrome(String str, int k){
42+
char[] c = str.toCharArray();
43+
int minChange = 0;
44+
for(int i=0,j=c.length-1;i<j;i++,j--)
45+
if(c[i] != c[j])
46+
minChange++;
47+
48+
if(minChange > k)
49+
return "-1";
50+
51+
int changeBoth = k - minChange;
52+
int i = 0;
53+
int j =c.length - 1;
54+
for(;i<=j;i++,j--){
55+
if(c[i] != c[j]){
56+
char maxChar = (char) Math.max(c[i],c[j]);
57+
if(maxChar != '9' && changeBoth - 1 >= 0){
58+
c[i] = '9';
59+
c[j] = '9';
60+
changeBoth--;
61+
}
62+
else{
63+
c[i] = maxChar;
64+
c[j] = maxChar;
65+
minChange--;
66+
}
67+
}
68+
else{
69+
char maxChar = (char) Math.max(c[i], c[j]);
70+
if (maxChar != '9' && changeBoth - 2 >= 0) {
71+
c[i] = '9';
72+
c[j] = '9';
73+
changeBoth -= 2;
74+
}
75+
}
76+
}
77+
if (changeBoth != 0 && i - 1 == j + 1) {
78+
c[i - 1] = '9';
79+
}
80+
String result = new String(c);
81+
return result;
82+
}
83+
public static void main(String[] args) {
84+
Scanner in = new Scanner(System.in);
85+
int n = in.nextInt();
86+
int k = in.nextInt();
87+
String str = in.next();
88+
System.out.println(maxPalindrome(str, k));
89+
}
90+
}

0 commit comments

Comments
 (0)