Monday, March 3, 2014

Count all distinct pairs with difference equal to k



-- If difference of curr and prev index value is equal to k, increment count by 1
-- curr greater than prev and difference of values less than k, increment curr.
-- curr greater than prev and difference of values legreater than k, increment prev.


static int countPairsWithDiffK(int a[], int k){
int n = a.length;
if(n == 0 || n == 1) return 0;
int count = 0, rem_curr = 0;
Arrays.sort(a);
for(int curr = 1, prev = 0; curr < n; )
{
if(a[curr] - a[prev] == k)
{
if(a[curr] != a[rem_curr])
{
System.out.println(a[curr]+", "+a[prev]);
count ++;
}
rem_curr = curr;
curr ++;
}
else if(curr > prev && a[curr] - a[prev] < k)
{
curr ++;
}else if(curr > prev && a[curr] - a[prev] > k)
{
prev ++;
}else curr ++;


}
return count;
}


References:
http://www.geeksforgeeks.org/count-pairs-difference-equal-k/

No comments:

Post a Comment