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.

Exactly what I am thinking, but not sure why this question appearnign wrong at the moment, it doesnt have all the parameters so its throwing error to me

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 →

Nice to have modern JavaScript:

nice. I looped through the array to count occurances of "max". Using filter makes it so much simpler.

这个filter很机智

Exactly what I am thinking, but not sure why this question appearnign wrong at the moment, it doesnt have all the parameters so its throwing error to me

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).Oh filter and result.length is so much simpler! Mine was a little longer

I used reduce to obtain the max, since spread operator can actually cause a stack overflow for large arrays.

You can filter out the max numbers from the array, and return its occurrance

You can make it shorter with a bit of chaining.