Highest Value Palindrome

  • + 0 comments
    def highestValuePalindrome(s, n, k):
        # Convert the string to a mutable list
        s = list(s)
        # Step 1: Identify mismatched mirrored pairs
        mismatches = []
        for i in range(n // 2):
            if s[i] != s[n - i - 1]:
                mismatches.append((i, n - i - 1))
    
        # Step 2: Check if we have enough changes to fix all mismatches
        if len(mismatches) > k:
            return "-1"  # Not enough changes to make it a palindrome
    
        # Step 3: Fix mismatched mirrored pairs
        for i, j in mismatches:
            # Use the larger of the two digits to fix the mismatch
            s[i] = s[j] = max(s[i], s[j])
            k -= 1  # Count this as one change
    
        # Step 4: Maximize the palindrome using remaining changes
        for i in range(n // 2):
            if k <= 0:
                break
    
            # If the current pair is not already '9', we can try to maximize it
            if s[i] != '9':
                # If this pair was previously fixed, it costs 1 change
                if (i, n - i - 1) in mismatches:
                    s[i] = s[n - i - 1] = '9'
                    k -= 1
                # If this pair was already a match, it costs 2 changes
                elif k >= 2:
                    s[i] = s[n - i - 1] = '9'
                    k -= 2
    
        # If the string has an odd length, we can change the middle character
        if n % 2 == 1 and k > 0:
            s[n // 2] = '9'
    
        # Return the resulting palindrome
        return ''.join(s)