Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* package codechef; // don't place package name! */
- import java.util.*;
- import java.lang.*;
- import java.io.*;
- /* Name of the class has to be "Main" only if the class is public. */
- public class Main
- {
- public static void main (String[] args) throws java.lang.Exception,IOException {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String[] firstLine = br.readLine().split(" ");
- int N = Integer.parseInt(firstLine[0]);
- int K = Integer.parseInt(firstLine[1]);
- String[] numsStr = br.readLine().split(" ");
- int[] nums = new int[N];
- for (int i = 0; i < N; i++) {
- nums[i] = Integer.parseInt(numsStr[i]);
- }
- Arrays.sort(nums);
- getC(N, K, nums);
- }
- private static void getC(int N, int K, int[] nums) {
- int i = 0, j = 1;
- long c = 0;
- while (j < N) {
- int d = nums[j] - nums[i];
- if (d < K) {
- j++;
- } else if (d > K) {
- i++;
- if (i == j) {
- j++;
- }
- } else {
- int c1 = 0, c2 = 0, p = nums[i], q = nums[j];
- if (d == 0) {
- while (nums[i] == p) {
- c1++;
- i++;
- j++;
- }
- c += c1 * (c1 - 1) / 2;
- // System.out.println("P1 " + c);
- // return;
- } else {
- while (i < N &&nums[i] == p) {
- c1++;
- i++;
- }
- while (j < N && nums[j] == q) {
- c2++;
- j++;
- }
- c += c1 * c2;
- }
- }
- }
- System.out.println(c);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement