DEV Community

Akande Joshua
Akande Joshua

Posted on

HackerRank: Birthday Cake Candles Solution using PHP (Algorithm)

Problem

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

candles = [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 candles[].

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

Constraints

1 <= n <= 10^5
1 <= candles[i] <= 10^7

Solution (How i solved it)

$mostFreq = -1;
    $maxFreq = 0;
    $size = sizeof($candles);
    $count = array_count_values($candles);
    for ($i = 0; $i < $size; $i++){
        $countFreq = 1;
        for ($j = 0; $j < $size; $j++){
            if ($candles[$i] == $candles[$j]){
            $countFreq++;
        }
        if ($maxFreq < $countFreq){
            $maxFreq = $countFreq;
            $mostFreq = $candles[$i];

        }else if ($maxFreq == $countFreq){
            $mostFreq = min($mostFreq, $candles[$i]);
        }
        return array_count_values($candles)[$mostFreq];
    }
}
Enter fullscreen mode Exit fullscreen mode

Link to the HackerRank: Birthday Cake Candles

Top comments (2)

Collapse
 
kalkwst profile image
Kostas Kalafatis

While experienced developers might understand your code easily, adding an explanation of your thought process and the algorithm used would be more helpful for new members of the community. It will also help you enhance your documentation and presentation skills.

Collapse
 
homezonic profile image
Akande Joshua

Thanks.
Will work on that henceforth.