We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.

Because it's horribly ineffiecient, causing it to time out (it takes more then 12 seconds so hackerrank cuts off the calculation to not waste processing power)

Because for every single item in the array it recalculates Math.max on the entire array, that's incredibly wastefull.

## Birthday Cake Candles

You are viewing a single comment's thread. Return to all comments →

You could even do this in a single line of code, like so:

`function birthdayCakeCandles(ar) {`

return ar.filter(i => i === Math.max(...ar)).length;

}

But I found that this causes recursion issues. This works perfectly fine though:

`function birthdayCakeCandles(ar) {`

var max = Math.max(...ar);

return ar.filter(i => i === max).length;

}

The first one is indeed overly complex, as it would search the max at each iteration

I used the reduce function instead, which allows for a single iteration, provided an extra local variable, like so

You can do it like this too:

I did exactly what you did, but half the test failed and couldn't figure out why :P

Because it's horribly ineffiecient, causing it to time out (it takes more then 12 seconds so hackerrank cuts off the calculation to not waste processing power)

Because for every single item in the array it recalculates Math.max on the entire array, that's incredibly wastefull.

That oneliner kind of works, but it's extremely slow because it recalculates Math.max(ar) for every single item.

You can avoid that by storing the value of Math max like this:

That way it's still short, but also blazing fast. (Math max is implicitly stored as

`f`

here).