Highest Value Palindrome
Highest Value Palindrome
+ 0 comments JavaScript Solution
let count = 0 let str = s.split('') for (let i = 0, j = n - 1; i <= j; i++, j--) { if (str[i] !== str[j]) count++ } if (count > k) return -1 for (let i = 0, j = n - 1; i <= j; i++, j--) { if (i === j) { if (k > 0) str[i] = '9'; break; } let available = (k - (str[i] !== '9') - (str[j] !== '9')) let needed = (count - (str[i] !== str[j])) if (available >= needed) { count -= (str[i] !== str[j]) k -= (str[i] !== '9') + (str[j] !== '9') str[i] = '9', str[j] = '9' } else { if (str[i] != str[j]) k--, count--; str[i] = str[j] = Math.max(str[i], str[j]); } // console.log(available, needed) } return str.join('')
+ 0 comments Here is my solution in java, javascript, python, C, C++, Csharp HackerRank Highest Value Palindrome Solution
+ 0 comments public static String highestValuePalindrome(String s, int n, int k) { char c [] = s.toCharArray(); int N=n/2; int j=-1; boolean [] B = new boolean [N]; for(int i=0;i<N; i++){ B[i]=c[i]==c[n-i-1]; if(!B[i]&&--k<0)return "-1"; c[i]=(char)(Math.max(c[i],c[n-i-1])); c[n-1-i]=c[i]; } while(k>0&&++j<N){ if(c[j]!='9'&&((B[j]&&k>1)||(k>0&&!B[j]))){ c[j]='9'; c[n-j-1]='9'; k=k+(B[j]?-2:-1); } } if(n%2==1&&k>0)c[N]='9'; return new String(c); } }
+ 0 comments Here Is the solution of Highest Value Palindrome Click Here
+ 1 comment All test cases passed
def highestValuePalindrome`(s, n, k) arr = s.split('') while (k > 0 && n > 1) firstIndex = 0 lastIndex = n - 1 while (firstIndex < lastIndex) if (arr[firstIndex] != arr[lastIndex]) if (arr[firstIndex] < arr[lastIndex]) arr[firstIndex] = arr[lastIndex] else arr[lastIndex] = arr[firstIndex] end k -= 1 end firstIndex += 1 lastIndex -= 1 end n -= 2 end if (k > 0) midIndex = n / 2 if (n.odd? && arr[midIndex] != '9' && k >= 1) arr[midIndex] = '9' k -= 1 end firstIndex = 0 lastIndex = n - 1 while (firstIndex < lastIndex && k >= 2) if (arr[firstIndex] != '9') arr[firstIndex] = '9' arr[lastIndex] =
Sort 498 Discussions, By:
Please Login in order to post a comment