Algorithm


Problem Name: Algorithms - Birthday Cake Candles

Problem Link: https://www.hackerrank.com/challenges/birthday-cake-candles/problem?isFullScreen=true

In this HackerRank Functions in Algorithms - Java programming problem solution,

You are in charge of the cake for a child's birthday. You have decided the cake will have one candle for each year of their total age. They will only be able to blow out the tallest of the candles. Count how many candles are tallest.

 

Example

candle = [4,4,1,3]

The maximum height candles are 4 units high. There are 2 of them, so return 2.

Function Description

 

Complete the function birthdayCakeCandles in the editor below.

 

birthdayCakeCandles has the following parameter(s):

 

  • int candles[n]: the candle heights

 

Returns

 

  • int: the number of candles that are tallest

Input Format

The first line contains a single integer n , the size of candle [].

The second line contains space-separated integers, where each integer i describes the height of candle [i].

Constraints

  • 1 <= n <= 10**5
  • 1 <= candle[i] <= 10**7

Sample Input 0

4
3 2 1 3

Sample Output 0

2

Explanation 0

Candle heights are [3,2,1,3] . The tallest candles are 3 units, and there are 2 of them.

 

 

 

 

 

Code Examples

#1 Code Example with C Programming

Code - C Programming


#include<stdio.h>:
int main()
{
    int i;
    int n;
    int max = 0;
    scanf("%d",&n);

    int a[n];
    int count = 0;

    for(i = 1; i  < = n; i++)
    {
        scanf("%d",&a[i]);
        if(max < a[i])
            max = a[i];
    }
    for(i = 1; i  < = n; i++)
        if(a[i] == max)
            count++;

    printf("%d\n",count>;
    return 0;
}
Copy The Code & Try With Live Editor

#2 Code Example with C++ Programming

Code - C++ Programming


#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <cstdlib>
#include <map>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

// Traverse all candles to find the highest candle, and traverse twice to find how many candles have this height!
// This can be done in one traverse as well. How?
// Well we can keep track of the number of candles of current highest height. 
// If we find a higher candle, we reset the counter.
// We will implement this method since the two traversal method is trivial.

int main() {
    int n;
    scanf("%d",&n);
    int highest = -1, cnt = 0;
    for (int i = 0;i  <  n; i++)
    {
        int h;
        scanf("%d",&h);
        if (h > highest)
        {
            highest = h;
            cnt = 1;
        }
        else if (h == highest) // Note this has to be "else if" not "if" !!
            cnt ++;
    }
    printf("%d\n", cnt);
}
Copy The Code & Try With Live Editor

#3 Code Example with Java Programming

Code - Java Programming


import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.regex.*;

public class Solution {

    // Complete the birthdayCakeCandles function below.
    static int birthdayCakeCandles(int[] ar) {
        int max=ar[0];
        for(int i = 1;i  <  ar.length; i++){
         if(max < ar[i]){
             max = ar[i];
         }   
        }
        int nb = 0;
        for(int j = 0; j  <  ar.length; j++){
            if(ar[j] == max){
                nb++;
            }
        }
        return nb;
    }

    private static final Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));

        int arCount = scanner.nextInt();
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        int[] ar = new int[arCount];

        String[] arItems = scanner.nextLine().split(" ");
        scanner.skip("(\r\n|[\n\r\u2028\u2029\u0085])?");

        for (int i = 0; i  <  arCount; i++) {
            int arItem = Integer.parseInt(arItems[i]);
            ar[i] = arItem;
        }

        int result = birthdayCakeCandles(ar);

        bufferedWriter.write(String.valueOf(result));
        bufferedWriter.newLine();

        bufferedWriter.close();

        scanner.close(>;
    }
}
Copy The Code & Try With Live Editor

#4 Code Example with Javascript Programming

Code - Javascript Programming


'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', inputStdin => {
    inputString += inputStdin;
});

process.stdin.on('end', _ => {
    inputString = inputString.replace(/\s*$/, '')
        .split('\n')
        .map(str => str.replace(/\s*$/, ''));

    main();
});

function readLine() {
    return inputString[currentLine++];
}

// Complete the birthdayCakeCandles function below.
function birthdayCakeCandles(ar) {
    let blownCandleCount = 0;
    
    let max = 0;
    
    for(let i = 0;  i  <  ar.length; i++){
        if(ar[i] > max){
            max = ar[i];
            blownCandleCount = 1;
        } else{
            if(max == ar[i]){
                blownCandleCount++;
            }
        }
    }
    return blownCandleCount;
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const arCount = parseInt(readLine(), 10);

    const ar = readLine().split(' ').map(arTemp => parseInt(arTemp, 10));

    let result = birthdayCakeCandles(ar);

    ws.write(result + "\n");

    ws.end();
}
Copy The Code & Try With Live Editor

#5 Code Example with Python Programming

Code - Python Programming


import math
import os
import random
import re
import sys

# Complete the birthdayCakeCandles function below.
def birthdayCakeCandles(ar):
    count=0
    big = max(ar)
    for i in range(len(ar)):
        if(ar[i] == big):
            count += 1
    return count
        

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    ar_count = int(input())

    ar = list(map(int, input().rstrip().split()))

    result = birthdayCakeCandles(ar)

    fptr.write(str(result) + '\n')

    fptr.close()
Copy The Code & Try With Live Editor

#6 Code Example with C# Programming

Code - C# Programming


using System;
using static System.Console;

class Solution
{
    static void Main(String[] args)
    {
        //No need to capture the size of array. I use array's length property instead.
        ReadLine();
        var height_temp = ReadLine().Split(' ');
        var height = Array.ConvertAll(height_temp, int.Parse);
        var maxValue = height[0];
        var maxValueOccurence = 1;

        for (int i = 1; i  <  height.Length; i++)
        {
            if (height[i] == maxValue)
            {
                maxValueOccurence++;
                continue;
            }
            if (height[i] > maxValue)
            {
                maxValue = height[i];
                maxValueOccurence = 1;
            }
        }
        WriteLine(maxValueOccurence);
    }
}
Copy The Code & Try With Live Editor

#7 Code Example with PHP Programming

Code - PHP Programming



Copy The Code & Try With Live Editor
Advertisements

Demonstration


Previous
[Solved] Mini-Max Sum in C, C++,Java, JavaScript, Python, PHP & C# solution in Hackerrank
Next
[Solved] Time Conversion in C, C++,Java, JavaScript, Python, PHP & C# solution in Hackerrank