Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
First, I started with sorting the array. I took 0th index as a pointer. I had the second pointer as 1st index. I incremented second pointer and tried to find out if the difference between values at the pointers is greater than 1. If this was the case I count the number between two pointers.
Then I incremented first pointer and repeated the process. I tried to find the greatest count of elements between pointers.
I created solution in:
All solutions are also available on my GitHub profile.
Scala
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import scala.io.Source import scala.util.control.Breaks._ object Solution extends App { val lines = Source.stdin.getLines().toList val elements = lines.tail.head.split(" ").map(_.toInt).sorted var maxDiffCount = 0 for(i <- 0 until elements.length -1) { breakable { for (j <- i + 1 until elements.length) { val diff = (elements(i) - elements(j)).abs if (diff > 1) { break } val diffCount = j - i maxDiffCount = Array(diffCount, maxDiffCount).max } } } println(maxDiffCount + 1) } |
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 |
import java.util.*; public class Solution { public static void main(String[] args) { Scanner stdin = new Scanner(System.in); int tests = stdin.nextInt(); int[] elements = new int[tests]; for(int i = 0; i < tests; i++) { elements[i] = stdin.nextInt(); } Arrays.sort(elements); int maxDiffCount = 0; for(int i = 0; i < elements.length - 1; i++) { for (int j = i + 1; j < elements.length; j++) { int diff = Math.abs(elements[i] - elements[j]); if (diff > 1) { break; } int diffCount = j - i; if(diffCount > maxDiffCount) { maxDiffCount = diffCount; } } } System.out.println(maxDiffCount + 1); stdin.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 |
import scala.io.Source import scala.util.control.Breaks._ object Solution extends App { val lines = Source.stdin.getLines().toList val elements = lines.tail.head.split(" ").map(_.toInt).sorted var maxDiffCount = 0 for(i <- 0 until elements.length -1) { breakable { for (j <- i + 1 until elements.length) { val diff = (elements(i) - elements(j)).abs if (diff > 1) { break } val diffCount = j - i maxDiffCount = Array(diffCount, maxDiffCount).max } } } println(maxDiffCount + 1) } |