Instagram
youtube
Facebook
Twitter

Python Largest and Second Largest Program Codechef Solution

Python's Largest and Second Largest Programme Codechef Solution

           Problem

You are given an array A of N integers.
Find the maximum sum of two distinct integers in the array.

Note: It is guaranteed that there are at least two distinct integers in the array.

          Input Format

  • The first line of input will contain a single integer T, denoting the number of test cases.
  • Each test case consists of multiple lines of input.
    • The first line of each test case contains a single integer N, which is the size of the array.
    • The next line contains N space-separated integers, denoting the array A.

           Output Format

For each test case, output on a new line the maximum sum of two distinct integers in the array.

           Constraints

  • 1<=T<=1000
  • 2<=N<=10^5
  • 1<=Ai<=1000
  • The sum of N over all test cases does not exceed 2.105.

Sample Input:

4 1 6

3 7 2 1 1 5 3

8 2 9 4 9

1 2

Sample Input:

10

12

17

3

           Explanation:

Test case 1: The maximum sum of two distinct elements is 4+ 6 = 10.

Test case 2: The maximum sum of two distinct elements is 7+ 5 = 12.

Test case 3: The maximum sum of two distinct elements is 8+ 9 = 17.

Test case 4: The maximum sum of two distinct elements is 1+ 2 = 3.

Solution:

n=int(input(“Enter the number of terms: “))

 

for i in range(n):

    size=int(input(“Enter the size of the array: “))

    array=list(map(int,input(“Enter array elements: “).split()))

    

    array2=list(set(array))

    array2.sort()

    

    print(array2[-2]+array2[-1])

 

Steps to solve this problem:

  1. Ask the user to enter the number of terms.
  2. In the loop, ask the user to enter the size of the array.
  3. Again, ask the user to enter the array elements, and using the map() function, get the iterator objects, convert them into a list, and store the list in the variable ‘array’.
  4. Convert the variable ‘array’ into a set using the set() function to remove the duplicate elements and the list() function to convert it into a list and store it in the variable ‘array’.
  5. Using the sort() function, arrange the elements in the list in ascending order.
  6. Now access the second- and third-largest elements in the list using the negative index values and print the result.