Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

High Value Palindrome #5

Open
prabaprakash opened this issue Jul 30, 2020 · 1 comment
Open

High Value Palindrome #5

prabaprakash opened this issue Jul 30, 2020 · 1 comment

Comments

@prabaprakash
Copy link
Owner

prabaprakash commented Jul 30, 2020

Algo

#include <bits/stdc++.h>

using namespace std;

string richieRich(string s, int n, int k){
   int lives=k;
   vector<bool> mod(n,false);  
   string temp(s); 
    
   for (int i=0;i<n/2;i++) 
   {
       if (temp[i]!=temp[n-i-1]) {mod[i]=true;lives--;}
       if (temp[i]<temp[n-i-1]) temp[i]=temp[n-i-1]; else if (temp[i]>temp[n-i-1]) temp[n-i-1]=temp[i];
       if (lives<0) return "-1";       
   }
    int j=0;
   while ((lives>0)&&(j<n/2))
   {
      if (temp[j]!='9'){
      if (mod[j]) lives++;
      if (lives>1) {temp[j]='9';temp[n-j-1]='9'; lives-=2;}
      }       
      j++;        
   }
    if (n%2==1) {if (lives>0) temp[n/2]='9';} 
    return temp;
}

int main() {
    int n;
    cin >> n;
    int k;
    cin >> k;
    string s;
    cin >> s;
    string result = richieRich(s, n, k);
    cout << result << endl;
    return 0;
}
@prabaprakash
Copy link
Owner Author

prabaprakash commented Jul 30, 2020

js solution

function highestValuePalindrome(s, n, k) {
    let lives = k;
    let mod = new Array(n).fill(false);
    let temp = s.split('');
    for (let i = 0; i < n / 2; i++) {
        let j = n - i - 1;
        if (temp[i] != temp[j]) {
            mod[i] = true;
            lives--;
        }
        if (temp[i] < temp[j])
            temp[i] = temp[j];
        else if (temp[i] > temp[j])
            temp[j] = temp[i];
        if (lives < 0)
            return "-1";
    }
    let j = 0;
    while ((lives > 0) && (j < n / 2)) {
        if (temp[j] != '9') {
            if (mod[j])
                lives++;
            if (lives > 1) {
                temp[j] = '9';
                temp[n - j - 1] = '9';
                lives -= 2;
            }
        }
        j++;
    }
    if (n % 2 == 1) {
        if (lives > 0)
            temp[Math.floor(n / 2)] = '9';
    }
    return temp.join('');
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant