Please help me with some more optimal solution..
- one of the simplest approach mentioned below
function maximumPalinUsingKChanges(str, k) {
let palin = str.split("");
let ans = "";
let l = 0;
let r = str.length - 1;
let changedArray = [];
while (l < r) {
if (str[l] != str[r]) {
palin[l] = palin[r] = Math.max(str[l], str[r]);
changedArray[l] = true;
k--;
}
l++;
r--;
}
if (k < 0) {
return "Not possible";
}
l = 0;
r = str.length - 1;
while (l <= r) {
if (palin[l] !== 9) {
if (changedArray[l] && k > 0) {
palin[l] = palin[r] = "9";
k--;
} else if (!changedArray[l] && k >= 2) {
palin[l] = palin[r] = "9";
k = k - 2;
}
}
if ((l === r) & (k > 0)) {
palin[l] = "9";
}
l++;
r--;
}
for (let i = 0; i < palin.length; i++) ans += palin[i];
return ans;
}
let str = "3493";
console.log(str.length);
let k = 1;
console.log(maximumPalinUsingKChanges(str, k));
approach reference Highest Value Palindrome
Thanks you!
Top comments (0)