Puzzle Description
Given \$N\$ numbers, \$N <= 10^5\$, count the total pairs of numbers \$(N_i, N_j)\$ that have a difference of \$K = N_i - N_j\$ where \$0 < K < 10^9\$.
Input Format:
1st line contains \$N\$ and \$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 number of pairs of numbers that have a difference \$K\$.
Time limit is 5 seconds.
Sample Input : 5 2 1 5 3 4 2 Sample Output: 3
First I've tried using ArrayList
s and later tried using arrays. The code is bad and does not at all follow 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:
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());
}
}