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
k
is 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;
}
}
Code Editor (Testing phase)
Improve Your Solution
Use the editor below to refine the provided solution. Select a programming language and try the following:
- Add import statement if required.
- Optimize the code for better time or space complexity.
- Add test cases to validate edge cases and common scenarios.
- Handle error conditions or invalid inputs gracefully.
- Experiment with alternative approaches to deepen your understanding.
Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.