The Smallest Pair | CodeChef Solution

Hello coders, today we are going to solve The Smallest Pair CodeChef Solution whose Problem Code is SMPAIR.

The Smallest Pair

Task

You are given a sequence a1, a2, …, aN. Find the smallest possible value of ai + aj, where 1 ≤ i < j ≤ N.

Input Format

The first line of the input contains an integer T denoting the number of test cases. The description of T test cases follows. 

The first line of each description consists of a single integer N.

The second line of each description contains N space separated integers – a1, a2, …, aN respectively.

Output Format

For each test case, output a single line containing a single integer – the smallest possible sum for the corresponding test case.

Constraints

  • T = 105N = 2 : 13 points.
  • T = 1052 ≤ N ≤ 10 : 16 points.
  • T = 10002 ≤ N ≤ 100 : 31 points.
  • T = 102 ≤ N ≤ 105 : 40 points.
  • 1 ≤ ai ≤ 106

Example

Sample Input

1
4
5 1 3 4

Sample Output

4

Explanation

Here we pick a2 and a3. Their sum equals to 1 + 3 = 4.

Solution – The Smallest Pair | CodeChef Solution

C++

#include<bits/stdc++.h>
using namespace std;

int main() {
    int n;
    cin>>n;
    while(n--){
    int m;
    cin>>m;
    int a[m];
    
    for(int i=0;i<m;i++){
        cin>>a[i];
    }
    
    sort(a,a+m);
    cout<<a[0]+a[1]<<endl;    
    }
	return 0;
}

Python

#Solution Provided by CodingBroz
T = int(input())
for i in range(T):
    n = int(input())
    s = list(map(int, input().split()))
    s.sort()
    print(s[0] + s[1])

Java

import java.io.FileNotFoundException;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(System.in);
        int t = sc.nextInt();
        int a;
        int m1, m2;
                  
        while(t-- > 0) {
            int n = sc.nextInt();
            m1 = Integer.MAX_VALUE; 
            m2=Integer.MAX_VALUE;
            for (int i = 0; i < n; i++) {
                a = sc.nextInt();
                if(a < m1) {
                    m2 = m1;
                    m1 = a;
                } else if(a >= m1 && a < m2) {
                    m2 = a;
                }
            }
            System.out.println(m1 + m2);
        }

        sc.close();
    }
}

Disclaimer: The above Problem (The Smallest Pair) is generated by CodeChef but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.

Leave a Comment

Your email address will not be published. Required fields are marked *