Chef and Eid Solution

Problem

During Eid, it's a tradition that each father gives his kids money which they can spend on entertainment.

Chef has N coins; let's denote the value of coin i by v_i. Since today is Eid, Chef is going to give one coin to each of his two children. He wants the absolute value of the difference between the values of coins given to the two children to be as small as possible, so that he would be as fair as possible.

Help Chef by telling him the minimum possible difference between the values of the coins given to the two children. Of course, Chef cannot give the same coin to both children.

Input

  • The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
  • The first line of each test case contains a single integer N.
  • The second line contains N space-separated integers v_1, v_2, \dots, v_N.

Output

For each test case, print a single line containing one integer — the minimum possible difference.

Constraints

  • 1 \le T \le 100
  • 2 \le N \le 10^5
  • the sum of N in all test cases does not exceed 5 \cdot 10^5
  • 1 \le v_i \le 10^6 for each valid i

Subtasks

Subtask #1 (30 points): the sum of N in all test cases does not exceed 2,000

Subtask #2 (70 points): original constraints

Sample 1:

Input
Output
2
3
1 4 2
3
1 3 3
1
0

Explanation:

Example case 1: Chef gives the coin with value 1 to his first child and the coin with value 2 to the second child, so the answer is 2-1 = 1.

Example case 2: Chef gives each of his children a coin with value 3, so the difference is 0.





Program :


 #include <stdio.h>

#include<stdlib.h>

int sub(void const *a,void const *b){

    return(*(int*)a - *(int*)b);

}

int main(){

    int t,i;

    scanf("%d",&t);

    for(i=0;i<t;i++)

    {

        int n;

        scanf("%d",&n);

        int a[n],j;

        for(j=0;j<n;j++)

        {

            scanf("%d",&a[j]);

        }

       

        qsort(a,n,sizeof(int),sub);

        int min=1000000;

        for(j=0;j<n-1;j++)

        {

            if(a[j+1]-a[j]<min&&a[j+1]-a[j]>=0)

            {

                min=a[j+1]-a[j];

            }

        }

        printf("%d\n",min);

        

    }

return 0;

}


Post a Comment

0 Comments