Wednesday, 13 February 2013

Given N numbers [N<=10^5], count the total pairs of numbers that have a difference of K

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package program;

import java.io.*;
import java.util.Arrays;
/**
 *
 * @author nishant gandhi
 */
public class Program {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
// N for no of values and K for difference
       int N,K;
       int count=0;
       BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
       String NK = br.readLine();
       String arr[]=NK.split(" ");
//Spliting first line by white space and assigning value to N & K
       N=Integer.parseInt(arr[0]);
       K=Integer.parseInt(arr[1]);
//array to store all inputs
       double []n=new double[N];
       NK = br.readLine();
       String data[]=NK.split(" ");
//splitting input second line with white space and assigning to separate string by string array data
//after that converting this string array to double array
       for(int i=0;i<data.length;i++)
       {
           n[i]=Double.parseDouble(data[i]);
       }
//soring array to check difference more efficiently
      Arrays.sort(n);
      //System.out.println("N:"+N);
      //System.out.println("K:"+K);
      for(int i=0;i<n.length;i++)    
      {
         
          for(int j=i;j<n.length;j++)
          {
              if(n[j]-n[i]==K)
              {
                  count++;
              }
             
          }
      }
       System.out.println(count);
      
      
      
      
      
      
      
    }
}

No comments:

Post a Comment