Join Regular Classroom : Visit ClassroomTech

Largest Even Unique Integer – Infytq 2019 Solve

Problem: Take a string as an input. Separate all the integers from it. Then take each integers only once and form the largest even number possible. Print the largest possible even number and if the even number cannot be made then returns -1.

Input Format: First line contains a single integer, the number of testcases n. Next n line contains n strings as input.

(NOTE: The actual problem didn’t have the number of testcases as input. But for your better convenience we have worked with testcases.)

Sample Input:

2
QWert@821142
infytq73119755

Sample Output:

8412
-1

Explanation: Here in the first example, Here the Largest even integer that can be made taking all the integers once (no repetition) is 8412

Here in the second case, largest even integer cannot be made taking all the integers once (no repetition) hence it returned -1.

Solution: We strongly recommend you to try the problem first before moving to the solution.

# Solution of longest unique even integer problem in Python 
# www.codewindow.in

def solve(str):
    import re
    
    digits=list(set(re.findall("\d", str)))
    digits.sort()   # Sorting accordinfg to the Ascii value
    digits.reverse()
    num=int(''.join(digits))    # Joining all the digits into one
    
    if(num%2==0):
        print(num)
    else:
        length=len(digits)
        for i in range(length-1, 0, -1):
            if int(digits[i])%2==0:
                d=digits[i]
                digits.remove(d)
                digits.insert(length-1, d)
                even_number=int(''.join(digits))
                
                print(even_number)
                break
        else:
            print("-1")

# Driver Code
test_case=int(input());     # Take number of testcases
while(test_case):
    str=input()
    solve(str)
    test_case-=1

Input:

2
QWert@821142
infytq73119755

Output:

8412
-1

Follow Us

You Missed