891956. Largest palindrome by changing at most K-digits
Largest palindrome by changing at most K-digits
Summary
Given a non-negative integer num and an integer k, find the largest palindromic number that can be obtained by changing at most k digits in the given number. A palindromic number is a number that remains the same when its digits are reversed.
Detailed Explanation
To solve this problem, we will iterate through all possible combinations of changing up to k digits in the given number and check if each combination results in a palindrome. We can use a recursive approach for this.
Here's a step-by-step breakdown of the solution:
- Initialize the maximum palindromic number as the given number.
- For each digit position from right to left (i.e., from least significant to most significant):
- If
kis greater than 0, change the current digit to all possible values (0-9) and recursively check if any of these combinations result in a palindrome.- If a larger palindromic number is found, update the maximum palindromic number.
- If
- Return the maximum palindromic number.
Time complexity: O(10^k * n), where n is the number of digits in the given number and k is the number of allowed changes. This is because we are iterating through all possible combinations of changing up to k digits.
Space complexity: O(n), as we need to store the current number and the maximum palindromic number at each recursive step.
Optimized Solutions
Java
public class Solution {
public int largestPalindrome(int n) {
long num = (long) Math.pow(10, n) - 1;
for (int i = n - 1; i >= 0; i--) {
if (k > 0 && i < n - 1) {
for (int j = 0; j <= 9; j++) {
num = num / 10 + j;
if (isPalindrome(num)) return (int) (num);
num = (long) Math.pow(10, n) - 1;
}
} else {
if (isPalindrome(num)) return (int) (num);
}
}
return -1;
}
public boolean isPalindrome(long num) {
long rev = 0, temp = num;
while (temp > 0) {
rev = rev * 10 + temp % 10;
temp /= 10;
}
return num == rev;
}
}