Given an array of integers and a target value, determine the number of pairs of array elements that have a difference equal to the target value.
Example:
Input: n=5, k=2, arr[]={1,5,3,4,2}
Output: 3
Explanation
There are 3 pairs of integers in the set with a difference of 2: [5,3], [4,2], and [3,1].
Approach
Java
import java.util.Arrays;public class Pairs {public static void main(String[] args) {int k = 2;int arr[] = { 1, 5, 3, 4, 2 };int res = pairs(k, arr);System.out.println(res);}static int pairs(int k, int[] arr) {Arrays.sort(arr);int n = arr.length;int i = 0, j = 1, diff, cnt = 0;while (j < n) {diff = arr[j] - arr[i];if (diff == k) {cnt++;j++;} else if (diff > k)i++;else if (diff < k)j++;}return cnt;}}
C++
#include <bits/stdc++.h>using namespace std;int main(){long long n = 5, k = 2;long long arr[n] = {1, 5, 3, 4, 2};sort(arr, arr + n);long long i = 0, j = 1, diff, cnt = 0;while (j < n){diff = arr[j] - arr[i];if (diff == k){cnt++;j++;}else if (diff > k)i++;else if (diff < k)j++;}cout << cnt << "\n";return 0;}
No comments:
Post a Comment