Skip to content

Instantly share code, notes, and snippets.

@1kohei1
Last active December 4, 2015 23:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 1kohei1/f393dab3ed3d12f17748 to your computer and use it in GitHub Desktop.
Save 1kohei1/f393dab3ed3d12f17748 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
import java.util.Arrays;
public class Playground {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = scanner.nextInt();
}
Arrays.sort(a);
if (n == 0 || n == 1) {
System.out.println(0);
return;
}
int aIndex = 1;
int bIndex = 0;
int count = 0;
while(aIndex + 1 != n || bIndex + 1 != n) {
int abs = Math.abs(a[aIndex] - a[bIndex]);
if (abs == k) {
count++;
if (aIndex + 1 == n) {
bIndex++;
} else {
aIndex++;
}
} else if (abs > k) {
bIndex += bIndex + 1 == n ? 0 : 1;
} else {
if (aIndex + 1 == n) {
bIndex++;
} else {
aIndex++;
}
}
}
System.out.println(count);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment