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
  • 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 →

  • alfruk
    2 months ago+ 0 comments

    Short version, easy to understand

    string highestValuePalindrome(string s, int n, int k) 
    {
        int i = 0;
        std::set< int > visited;
        
        while ( i < s.size() )
        {
            if ( s[ i ] != s[ n - i - 1 ] )
            {
                if ( k == 0 ) return "-1";
                auto value = std::max( s[ i ], s[ n - i - 1 ] );
                s[ i ] = s[ n - i - 1 ] = value;
                k--;
                visited.insert( i );
            }
            i++;
        }
    
        // in here s is a palindrome
    
        i = 0;
        while ( i < s.size() && k > 0 )
        {
            if ( s[ i ] != '9' )
            {
                if ( visited.find( i ) != visited.end() )
                {
                    s[ i ] = s[ n - i - 1 ] = '9';
                    k--;
                }
                else if ( k >= 2 )
                {
                    s[ i ] = s[ n - i - 1 ] = '9';
                    k -= 2;
                }
            }
            
            i++;
        }
        
        if ( n % 2 == 1 && k > 0 ) s[ n/2 ] = '9';
    
        return s;
    }
    
    0|
    Permalink
  • Blog
  • Scoring
  • Environment
  • FAQ
  • About Us
  • Support
  • Careers
  • Terms Of Service
  • Privacy Policy