Hackerrank – Problem Statement A description of the problem can be found on Hackerrank. Solution I created solution in: Scala Java JavaScript 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 24 25
|
object PriyankaAndToys extends App { val lines = Source.stdin.getLines().toList val n = Integer.parseInt(lines.head) val weights = lines.tail.head.split("\\s+").map(_.toInt).sorted var price = 1 var lastWeight = weights(0) var i = 1 while ( { i < weights.length }) { if (lastWeight + 4 >= weights(i)) { // lastWeight = toys[i]; } else { price += 1 lastWeight = weights(i) } { i += 1; i - 1 } } println(price) } |
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 33 34 35 36 37
|
import java.util.Arrays; import java.util.Scanner; public class PriyankaAndToys { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = Integer.parseInt(scanner.nextLine()); String[] weights = scanner.nextLine().split("\\s+"); int[] toyWeights = new int[n]; for (int i = 0; i < n; i++) { toyWeights[i] = Integer.parseInt(weights[i]); } Arrays.sort(toyWeights); int price = 1; int lastWeight = toyWeights[0]; for (int i = 1; i < toyWeights.length; i++) { if(lastWeight + 4 >= toyWeights[i]) { // lastWeight = toys[i]; } else { price++; lastWeight = toyWeights[i]; } } System.out.println(price); scanner.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 26 27 28 29 30
|
'use strict'; const processData = input => { const lines = input.split('\n'); const n = parseInt(lines[0]); const weights = lines[1].split(" ").map(i => parseInt(i)).sort((a, b) => a - b); let price = 1; let lastWeight = weights[0]; for (let i = 1; i < weights.length; i++) { if(lastWeight + 4 >= weights[i]) { // lastWeight = toys[i]; } else { price++; lastWeight = weights[i]; } } console.log(price); }; process.stdin.resume(); process.stdin.setEncoding("ascii"); let _input = ""; process.stdin.on("data", input => _input += input); process.stdin.on("end", () => processData(_input)); |