Sunday, May 10, 2020

Find the smallest sum of the two numbers formed using a list of numbers

Q. Find the smallest sum of the two numbers formed using a list of numbers, such that each number of the list is used to form the two numbers.
The first line of input contains an integer T denoting the number of test cases. Then T test cases follow. First line of each test case contains an integer N denoting the size of the array. Next line of each test contains N space seperated integers denoting the elements of the array.

Solution:
The answer is the sum of the two smallest numbers that can be formed using a list of numbers.
To construct the smallest two numbers, first we sort the given list in ascending order.
Then we take alternate digits from the list and form the two numbers. Finally we add the two to get the answer.

# Solution in Python
t= int(input())
while(t>0):
    n=int(input())
    a=list(map(int,input().split()))
    a.sort()
    q1=[]
    q2=[]
    n1= 0
    n2= 0
    for i in range(len(a)):
        if(i%2==0):
            q1.append(a[i])
        else:
            q2.append(a[i])
    for j in reversed(range(len(q1))):
        n1 = n1 + q1.pop(0)*10**(j)
    for k in reversed(range(len(q2))):
        n2 = n2 + q2.pop(0)*10**(k)
    print(n1+n2)
    t -= 1


Queue in Python https://www.geeksforgeeks.org/queue-in-python/

No comments:

Post a Comment

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows