Chef and New Year Gifts Solution

Problem

Chef wants to give his friends Alice and Bob some gift on the occasion of new year!

He visits a gift shop with n gifts placed in row. The i^{th} gift has a price p_i. Chef doesn't want to give the same gift to both his friends. Yet he wants the gifts to be as equal as possible, in other words he wants the absolute difference between the prices of both gifts to be as less as possible.

Help Chef in determining the least absolute difference in prices of the gifts given to Alice and Bob.

Input Format

  • First line of the input contains a single integer T, the number of test cases. The description of each test case follows.
  • The first line of each test case contains a single integer n.
  • The next line contains n space-separated integers, i^{th} of them denoting the price of the i^{th} gift.

Output Format

For each test case, print the minimum absolute difference in both the gifts in a separate line.

Constraints

  • 1 \le T \le 10
  • 2 \le n \le 5000
  • 1 \le p_i \le 10^9

Sample 1:

Input
Output
3
5
1 2 2 7 8
4
9 1 6 4
2
8 9
0
2
1

Explanation:

  • In the first test case, you can pick gifts with prices 2 and 2. Hence the minimum absolute difference is 0.






Program :


 #include <math.h>

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#include <assert.h>

#include <limits.h>

#include <stdbool.h>

int c_int( const void* a, const void* b )

{

    if( *(int*)a == *(int*)b ) 

    return 0;

    return *(int*)a < *(int*)b ? -1 : 1;

}

int main()

{

    int n,t,i;

    scanf("%d",&t);

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

    {

    scanf("%d",&n);

    int *a = malloc(sizeof(int) * n);

    for(int a_i = 0; a_i < n; a_i++)

    {

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

    }

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

    int min = abs(a[1] - a[0]);

    for(int i=1; i<n-1; ++i)

    {

        if( abs(a[i] - a[i+1]) < min ) 

        min = abs(a[i] - a[i+1]);

    }

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

    }

    return 0;

}

Post a Comment

0 Comments