Java code to find Count of Pairs in Integer Array with Absolute Difference K

Let's solve a LeetCode problem using Java. 

Count Number of Pairs With Absolute Difference K

You can go through the problem and try to understand what needs to be done. Try to write your own code first. We have solved the problem and its here for your reference.

 * Count Number of Pairs With Absolute Difference K
 * @author
 * @param nums
 * @param k
 * @return
public int countKDifference(int[] nums, int k) {

	int count = 0;

	for (int i = 0; i < nums.length; i++) {
		for (int j = i + 1; j < nums.length; j++) {
			if (Math.abs(nums[i] - nums[j]) == k) {
	return count;

If you look closely, we have looped through the Integer Array, and compared two elements of the arrays and find the difference between them. Now the difference can be positive or negative but it has to be equal to the input K. So we've used Math.abs() function to find the absolute value. Whenever we encounter an absolute value, we increment our counter. 

At the end, we return the counter. 

Thanks for Reading the Article. If you have reached this far, we hope that the article was useful to you! Please Like/Share/Follow us on FacebookTwitterTumblrLeetCode 


Popular posts from this blog

Calculate Your CTC Salary Hike Percentage - Online Calculator to find your New Salary

Find the Longest Streak of 1's in a Binary Array using Java Code

Java Program to Read a Properties file and return a Property Value

Create a File logging Utility using Java Code

What is my IP Address - How to find your IP address on Local Network using Command Prompt, and External Network using JavaScript Code