Count All Distinct Pairs with a difference equal to k. 1 repetition is allowed



 Count All Distinct Pairs with a difference equal to k. 1 repetition is allowed
Count All Distinct Pairs with a difference equal to k. 1 repetition is allowed 









This problem is a test conduct by hackerrank site.


In this problem an array is given with some integer value and a set value k is also given, now the task is find the distinct pair of record with a set of K value

public static int kDifference(List<int> a, int k) { //write code here }

static void Main(string[] args) { Console.WriteLine("Enter the No you want to add"); int aCount = Convert.ToInt32(Console.ReadLine().Trim()); //aCount have user input List<int> a = new List<int>();// creating a list for (int i = 0; i < aCount; i++) { int aItem = Convert.ToInt32(Console.ReadLine().Trim()); a.Add(aItem);//adding value in list } Console.WriteLine("Enter the set No K Value"); int k = Convert.ToInt32(Console.ReadLine().Trim()); int result = kDifference(a, k);//calling method Console.WriteLine(result); Console.ReadLine(); }
Solution:
 I am too much comfortable with array that’s why I am using array to solve this
problem.
Main logic behind the problem is :
For eg:
string 1 3 5 and k =2
where k represent 2 distinct string i.e (1,3) and (3,5) , one value repetition is allow logic:  1-3==k or 3-5==k where k =2 then count++;
1– 3= 2 which is true
3– 5 = 2 which is also true

public static int kDifference(List<int> a, int k) { int[] arr = new int[a.Count]; int count = 0; int l=0; foreach (var item in a) { arr[l] = item; l++; } for (int i = 0; i < a.Count - 1; i++) { for (int j = i + 1; j < a.Count; j++) { if (arr[i] - arr[j] == k || arr[j] - arr[i] == k) count = count + 1; } } return count; }





Share:

No comments:

Post a Comment

Popular

Tags

Mobile

Recent Posts