#C4227. Counting Pairs with Limited Difference

    ID: 47742 Type: Default 1000ms 256MiB

Counting Pairs with Limited Difference

Counting Pairs with Limited Difference

You are given an array of N integers and an integer k. Your task is to count the number of pairs \((i,j)\) such that \(i < j\) and the absolute difference between Ai and Aj is at most \(k\), i.e.,

[ |A_i - A_j| \le k ]

The array may be unsorted, and the straightforward approach of examining every pair would be too slow for large inputs. A more optimal approach involves sorting the array and then using a two-pointer technique to efficiently count all valid pairs.

inputFormat

The input is given from stdin and consists of three lines:

  1. The first line contains an integer \(N\) representing the number of elements in the array.
  2. The second line contains \(N\) space-separated integers representing the elements of the array.
  3. The third line contains an integer \(k\) representing the maximum allowed difference.

outputFormat

Output a single integer to stdout which is the number of pairs \((i,j)\) that satisfy the condition \(|A_i - A_j| \le k\).

## sample
3
1 3 5
2
2

</p>