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

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →