Search This Blog

Sunday, September 1, 2013

Hacker Rank Problem - Search - Pairs

Pairs

The following is the solution to the Hacker Rank problem "Pairs". For other Hacker Rank problem solutions visit my Hacker Rank Solutions Page.
Scored: 39/39
/**
 * @author Arun.G
 *
 */

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.Scanner;
public class Solution {

    public static void main(String[] args) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
        Scanner sc=new Scanner(System.in);
        int n=0,k=0,count=0;
        n= sc.nextInt();
        k=sc.nextInt();
        ArrayList<Integer> list = new ArrayList<Integer>();
        while(sc.hasNextInt())
            list.add(sc.nextInt());
       
        int numa=0,numb=0;
        Collections.sort(list);
        for(int i=0;i<list.size();i++)
        {
            numa = (int)list.get(i);
            for(int j=i+1;j<list.size();j++)
            {
              numb = (int)list.get(j);
              if(numa<numb)
              {
                if(Math.abs(numa-numb)==k)
                    count++;
                if(Math.abs(numa-numb)>k)
                    break;
              }
              else
              {
                j=i;
              }
            }
                   
        }
        System.out.println(count);
        sc.close();
    }

}


No comments:

Post a Comment

Labels