Problem Statement
A description of the problem can be found on Hackerrank.
Solution
Sort the array. Choose one element and check continously every next element after chosen element if their difference is equals to k
. If it is greater stop comparisons and choose next element.
Note: JavaScript and Ruby solutions use the same algorithm as other solutions, but some Hackerrank tests failed on timeout.
I created solution in:
All solutions are also available on my GitHub.
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.util.Arrays; import java.util.Scanner; public class Pairs { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int k = in.nextInt(); int[] ar = new int[n]; for(int i = 0; i < n; i++){ ar[i] = in.nextInt(); } Arrays.sort(ar); int pairs = 0; for(int i = 0; i < ar.length; i++) { for(int j = i + 1; j < ar.length; j++) { if(ar[j] - ar[i] == k) { pairs++; break; } } } System.out.println(pairs); in.close(); } } |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
'use strict'; const processData = input => { let lines = input.split('\n'); let definition = lines[0].split(' ').map(i => parseInt(i)); let difference = definition[1]; let array = lines[1].split(' ').map(i => parseInt(i)); let sortedArray = array.sort((a, b) => a - b); let pairs = 0; for(let i = 0; i < sortedArray.length - 1; i++) { for(let j = i + 1; j < sortedArray.length; j++) { if(sortedArray[j] - sortedArray[i] == difference) { pairs++; } } } console.log(pairs); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); var _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 |
(length, diff) = gets.split.map{|s| s.to_i} arr = gets.split.map{|s| s.to_i}.sort{|a,b| a <=> b} pairs = 0 for i in 0...arr.size - 1 for j in (i+1)...arr.size if(arr[j] - arr[i] == diff) pairs += 1 break end end end puts pairs |
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import scala.io.Source import scala.util.control.Breaks._ object Pairs extends App { val lines = Source.stdin.getLines().toList val definition = lines(0).split(" ").map(_.toInt) val diff = definition(1) val array = lines(1).split(" ").map(_.toInt).sorted var pairs = 0 (0 until array.length - 1).foreach(i => { breakable { (i + 1 until array.length).foreach(j => { if (array(j) - array(i) == diff) { pairs += 1 break } }) } }) println(pairs) } |