'Birthday Cake Candles HackerRank withoug Math.max Javascript
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 of candles is 4 units high. There are 2 of them, so return 2.
So basically the way I'm doing so is by moving from each place of the array comparing each other with two for cycles, the second cycle will count the repeated numbers, some people use Math.max imported function but I didn't know it before started looking for the answer, and I think this way should work, but can't get to the answer, any ideas?
function birthdayCakeCandles(candles) {
let height=1;
let b=0;
for (let i=0; i<candles.length; i++)
{
for (b=0; b<candles.length; b++)
{
if(b!=i && candles[b]===candles[i])
{height++;}
b++;
}
}
return height;
Solution 1:[1]
This should be straightforward, iterate through the array find max if max exists again increase count, if some other element greater than max set it to max and reset count to 1
function findTallestCandleCount(candles){
let max = 0, count = 0
for (let candle of candles) {
if (candle > max) {
max = candle
count = 1
} else if (candle === max){
count++
}
}
return count;
}
Solution 2:[2]
I solved it this way
function birthdayCakeCandles(candles) {
let height=0;
let max=Math.max(...candles);
for (let i=0; i<candles.length; i++)
{
if (candles[i]==max)
{height++;}
}
return height;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | HariHaravelan |
| Solution 2 | David Isea |
