Hackerrank – Problem Statement
A description of the problem can be found on Hackerrank.
Solution
We find the highest candles. Then we find count of candles with max height.
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 |
object BirthdayCakeCandles { def birthdayCakeCandles(n: Int, ar: Array[Int]): Int = { val candleHeightGroups: Map[Int, Seq[Int]] = ar.toList.groupBy(i => i) val maxHeight = candleHeightGroups.keys.max candleHeightGroups.getOrElse(maxHeight, Seq.empty).size } def main(args: Array[String]) { val sc = new java.util.Scanner (System.in) val n = sc.nextInt() val ar = new Array[Int](n) for(ar_i <- 0 until n) { ar(ar_i) = sc.nextInt() } val result = birthdayCakeCandles(n, ar) println(result) } } |
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 BirthdayCakeCandles { static int birthdayCakeCandles(int n, int[] ar) { int max = 0; for(int i = 0; i < ar.length; i++) { if(ar[i] > max) { max = ar[i]; } } int count = 0; for(int i = 0; i < ar.length; i++) { if(ar[i] == max) { count++; } } return count; } public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int[] ar = new int[n]; for(int ar_i = 0; ar_i < n; ar_i++){ ar[ar_i] = in.nextInt(); } int result = birthdayCakeCandles(n, ar); System.out.println(result); } } |
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
'use strict'; process.stdin.resume(); process.stdin.setEncoding('ascii'); var input_stdin = ""; var input_stdin_array = ""; var input_currentline = 0; process.stdin.on('data', function (data) { input_stdin += data; }); process.stdin.on('end', function () { input_stdin_array = input_stdin.split("\n"); main(); }); function readLine() { return input_stdin_array[input_currentline++]; } /////////////// ignore above this line //////////////////// function birthdayCakeCandles(n, ar) { let max = 0; for(let i = 0; i < ar.length; i++) { if(ar[i] > max) { max = ar[i]; } } let count = 0; for(let i = 0; i < ar.length; i++) { if(ar[i] === max) { count++; } } return count; } function main() { var n = parseInt(readLine()); const ar = readLine().split(' ').map(i => parseInt(i)); var result = birthdayCakeCandles(n, ar); process.stdout.write("" + result + "\n"); } |