Highest Value Palindrome


Problem Statement :


Palindromes are strings that read the same from the left or right, for example madam or 0110.

You will be given a string representation of a number and a maximum number of changes you can make. Alter the string, one digit at a time, to create the string representation of the largest number possible given the limit to the number of changes. The length of the string may not be altered, so you must consider 0's left of all higher digits in your tests. For example 0110 is valid,  0011 is not.

Given a string representing the starting number, and a maximum number of changes allowed, create the largest palindromic string of digits possible or the string '-1' if it is not possible to create a palindrome under the contstraints.


Function Description

Complete the highestValuePalindrome function in the editor below.

highestValuePalindrome has the following parameter(s):

string s: a string representation of an integer
int n: the length of the integer string
int k: the maximum number of changes allowed

Returns

string: a string representation of the highest value achievable or -1

Input Format

The first line contains two space-separated integers, n and k, the number of digits in the number and the maximum number of changes allowed.
The second line contains an n-digit string of numbers.

Constraints

0  <=  n  <=  10^5
0  <=  k  <=  10^5
Each character i in the number is an integer where 0  <=  i  <=  9.



Solution :



title-img


                            Solution in C :

In  C++ :







#include <bits/stdc++.h>

using namespace std;

int N, K;
int A[100000];
int B[100000];

int main()
{
    scanf("%d%d", &N, &K);
    char c;
    for(int i=0; i<N; i++)
    {
        scanf(" %c", &c);
        A[i]=c-'0';
    }
    for(int i=0; i<N-i-1; i++) if(A[i]!=A[N-i-1])
    {
        if(A[i]>A[N-i-1])
            A[N-i-1]=A[i], B[N-i-1]=1;
        else
            A[i]=A[N-i-1], B[i]=1;
        K--;
    }
    if(K<0)
        printf("-1\n");
    else
    {
        for(int i=0; i<=N-i-1; i++) if(A[i]!=9)
        {
            int cost=2;
            if(i==N-i-1)
                cost=1;
            if(B[i])
                cost--;
            if(i!=N-i-1 && B[N-i-1])
                cost--;
            if(K>=cost)
            {
                K-=cost;
                A[i]=A[N-i-1]=9;
            }
        }
        for(int i=0; i<N; i++)
            printf("%d", A[i]);
        printf("\n");
    }
    return 0;
}









In  Java  :







import java.util.Scanner;

public class Solution {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int n = scanner.nextInt();
        int k = scanner.nextInt();
        char[] c = scanner.next().toCharArray();
        boolean[] ch = new boolean[n];
        for (int i = 0; i < n/2; ++i) {
            if (c[i] != c[n - i - 1]) {
                c[i] = c[n - i - 1] = (char)Math.max(c[i], c[n - i - 1]);
                ch[i] = true;
                --k;
            }
        }
        if (k < 0) {
            System.out.println(-1);
            return;
        }
        for (int i = 0; i < n/2; ++i) {
            if (c[i] != '9') {
                if (ch[i] && k > 0) {
                    c[i] = c[n - i - 1] = '9';
                    --k;
                }
                if (!ch[i] && k > 1) {
                    c[i] = c[n - i - 1] = '9';
                    k -= 2;
                }
            }
        }
        if (n % 2 == 1 && k > 0) {
            c[n/2] = '9';
        }
        System.out.println(new String(c));
    }
}








In   C  :






#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main() {
    int n,k,i,l,r;
    scanf("%d %d",&n,&k);
    char str[n+1];
    char hash[n];
    scanf("%s",str);
    for(i=0;i<n;i++){
        hash[i] = '0';
    }
    l=0,r=n-1;
    while(l<r){
        if(str[l]!=str[r]){
            if(k==0){
                printf("-1");
                return 0;
            }
            if(str[l]<str[r]){
                str[l] = str[r];
                hash[l] = '1';
            }
            else{
                str[r] = str[l];
                hash[r] = '1';
            }
            k--;
        }
        l++;
        r--;
    }
    l=0,r=n-1;
    while(l<r && k>0){
        if(str[l]!='9'){
            if(hash[l]=='1'||hash[r]=='1'){
                str[l] = str[r] = '9';
                k--;
            }
            else if(k>1){
                str[l] = str[r] = '9';
                k-=2;
            }
        }
        l++;
        r--;
    }
    if(l==r && k>0)
        str[l] = '9';
    printf("%s",str);
    return 0;
}









In   Python3 :





l, k = input().split(' ')
l = int(l)
k = int(k)
n = list(input())
midl = int(len(n)/2)


diff = 0
for i in range(0,midl):
    if (n[i] != n[l-1-i]):
        diff += 1

if (diff > k):
    print(-1)
    exit(0)

more = k - diff

count = 0
for i in range(0,midl):
    if (n[i] == n[l-1-i]):
        if (n[i] != '9' and more >= 2):
            n[i], n[l-1-i] = '9', '9'
            more -= 2
        continue
    maxn = n[i] if (n[i] > n[l-1-i]) else n[l-1-i]
    if (maxn != '9' and more >= 1):
        more -= 1
        maxn = '9'
    n[i], n[l-1-i] = maxn, maxn
    #count += 1

if (more > 0):
    n[midl] = '9'
        
print("".join(n))
                        








View More Similar Problems

Polynomial Division

Consider a sequence, c0, c1, . . . , cn-1 , and a polynomial of degree 1 defined as Q(x ) = a * x + b. You must perform q queries on the sequence, where each query is one of the following two types: 1 i x: Replace ci with x. 2 l r: Consider the polynomial and determine whether is divisible by over the field , where . In other words, check if there exists a polynomial with integer coefficie

View Solution →

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →