We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
  • HackerRank Home

    HackerRank

  • |
  • Prepare
  • Certify
  • Compete
  • Apply
  • Hiring developers?
  1. Prepare
  2. Algorithms
  3. Strings
  4. Highest Value Palindrome
  5. Discussions

Highest Value Palindrome

Problem
Submissions
Leaderboard
Discussions
Editorial

    You are viewing a single comment's thread. Return to all comments →

  • MyLove_MyFall
    6 months ago+ 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|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy