import java.util.Scanner;
public class k_diff {
public int process() {
Scanner scanner = new Scanner(System.in);
int total_nums = scanner.nextInt();
int diff = scanner.nextInt();
int ary_nums[] = new int[total_nums];
for (int i = 0; i < total_nums; i++) {
ary_nums[i] = scanner.nextInt();
}
int len = ary_nums.length;
int count = 0;
for (int j = 0; j < len - 1; j++) {
for (int k = j + 1; k < len; k++) {
if (Math.abs(ary_nums[j] - ary_nums[k]) == diff) {
count++;
}
}
}
return count;
}
public static void main(String args[]) {
k_diff kdiff = new k_diff();
System.out.println(kdiff.process());
}
}
Puzzle Description
Given N numbers, [N<=10^5] we need to count the total pairs of numbers that have a difference of K. [K>0 and K<1e9]
Input Format:
1st line contains N & K (integers).
2nd line contains N numbers of the set. All the N numbers are assured to be distinct.
Output Format:
- One integer saying the no of pairs of numbers that have a diff K.
How can I improve the above code, to make it faster.
- Time limit is 5secs
- Given N numbers N<=10^5
Sample Input : 5 2
1 5 3 4 2
Sample Output: 3
First I've tried using ArrayLists, later tried using arrays. Code written is bad and not at all followed normal conventions of java, but I'm not looking at that, because execution time doesn't depend on it, right? But to achieve the puzzle description I couldn't see any better logic than this.