Difference of pair of elements is N

Given an unsorted array Arr[] and a number N. You need to write a program to find if there exists a pair of elements in the array whose difference is N. If the pair is found print 1 otherwise print -1.

Sample Input
2
6 78
5 20 3 2 5 80
5 45
90 70 20 80 50
Sample Output
1
-1
#include<stdlib.h>
#include<stdio.h>
#include<math.h>
int main() {
  int t, n, arr[20], i, j, k, key, flag[10];
  scanf("%d",&t);
  for(i=0;i<t;i++){
    scanf("%d%d",&n,&key);
    for(j=0;j<n;j++)
      scanf("%d",&arr[j]);
    for(j=0;j<n-1;j++){
      for(k=j+1;k<n;k++){
        if(key==abs(arr[j]-arr[k]))
          break;
      }
      if(k<n)
        break;
    }
    if(j<n-1)
      flag[i] = 1;
    else
      flag[i] = -1;
  }
  for(i=0;i<t;i++){
    printf("%d",flag[i]);
    if(i<t-1)
      printf("\n");
  }
  return 0;
}

No comments:

Post a Comment

Total Pageviews