Showing posts with label Java Program to Count all distinct pairs with difference equal to k. Show all posts
Showing posts with label Java Program to Count all distinct pairs with difference equal to k. Show all posts

Monday, 28 May 2018

Java Program to Count all distinct pairs with difference equal to k


Given an integer array and a positive integer k, count all distinct pairs with difference equal to k.

Example:-

arr[]:-{1, 5, 3, 4, 2}, k = 3
Output: 2
2 pairs({1, 4} and {5, 2}) with difference equal to 3.

Sample Program:-

package com.shc.ecom.payment.web.rest;  
 /**  
  * @author sdixit  
  *  
  */  
 public class Example {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int arr[] = { 1, 5, 3, 4, 2 };  
           int k = 3;  
           System.out.println("Count of pairs :-" + countPairsWithDiffK(arr, k));  
      }  
      private static int countPairsWithDiffK(int[] arr, int k) {  
           int count = 0;  
           int n = arr.length;  
           for (int i = 0; i < n; i++) {  
                for (int j = i + 1; j < n; j++)  
                     if (arr[i] - arr[j] == k || arr[j] - arr[i] == k)  
                          count++;  
           }  
           return count;  
      }  
 }  


Sample Output:-
 Count of pairs :-2  

Enjoy Programming.