-
Notifications
You must be signed in to change notification settings - Fork 0
/
Highest Maximum Palindrome.cpp
75 lines (70 loc) · 1.83 KB
/
Highest Maximum Palindrome.cpp
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
72
73
74
75
bool checkPalindrome(string s){
int start = 0;
int end = s.length() - 1;
while(start <= end){
if(s[start] != s[end]){
return false;
}
start++;
end--;
}
return true;
}
string highestValuePalindrome(string s, int n, int k) {
string ans = "";
int start = 0, end = s.length() - 1;
vector<bool> changed(n, false);
// track of changed positions
while(start <= end){
if(s[start] != s[end]){
if(k >= 1 && (s[start] == '9' || s[end] =='9')){
s[start] = '9';
s[end] = '9';
k--;
changed[start] = changed[end] = true;
}
else if (k >= 2 && s[start] != '9' && s[end] !='9'){
s[start] = '9';
s[end] = '9';
k -= 2;
changed[start] = changed[end] = true;
}
else if (k > 0){
char maxi = max(s[start], s[end]);
s[start] = maxi;
s[end] = maxi;
k--;
changed[start] = changed[end] = true;
}
}
start++;
end--;
}
// Second pass to make highest value palindrome
start = 0;
end = s.length() - 1;
while(start <= end && k > 0){
if(start == end && k > 0){
// middle element in odd length strings
s[start] = '9';
k--;
}
if(s[start] < '9'){
if(changed[start] && k >= 1){
s[start] = s[end] = '9';
k--;
}
else if(!changed[start] && k >= 2){
s[start] = s[end] = '9';
k -= 2;
}
}
start++;
end--;
}
if(checkPalindrome(s)){
return s;
} else {
return "-1";
}
}