# Birthday Cake Candles

# Birthday Cake Candles

apghr + 21 comments A compact C++ solution:

#include <iostream> int main(){ int c, n, max = 0; std::cin.ignore(); while(std::cin >> n) max < n ? c = !!(max = n) : c += max == n; std::cout << c; return 0; }

v1nea + 1 comment Like this a lot. Thanks.

mohammedavez85 + 3 comments `c

# include

# include

# include

# include

# include

# include

# include

int birthdayCakeCandles(int n, int ar_size, int* ar) { // Complete this function int i,j,temp,count=0,b; for(i=0;i

`b=ar[0]; for(i=0;i<n;i++){ if(b == ar[i]){ count++; } }`

return count; }

int main() { int n,ar_i; scanf("%i", &n); int *ar = malloc(sizeof(int) * n); for(ar_i = 0; ar_i < n; ar_i++){ scanf("%i",&ar[ar_i]); } int result = birthdayCakeCandles(n, n, ar); printf("%d\n", result); return 0; } BRO THIS CODE SAYS TIME LIMIT EXCEEDED PLEASE HELP

Yakubk_98 + 5 comments use c++ and you'll be fine

int birthdayCakeCandles(int n, vector <int> ar) { // Complete this function int max = ar[0]; int count = 0; for(int i=0; i<n; i++) if(ar[i] > max) max = ar[i]; for(int i = 0; i < n; i++) if (ar[i] == max) count++; return count; }

sandeepkataria + 4 comments this code was working on some test case but not all please help me

vaishaligarg2012 + 5 comments /*You should do like this... */

int max=ar[0]; int count=0; for(int i=0;i<n;i++){ if(ar[i]>max){ max=ar[i]; } } for(int i=0;i<n;i++){ if(ar[i]==max){ count++; } } return count;

jdanielys07 + 1 comment In java, maybe this way can help you! :)

if(ar!=null && ar.length>0 && n>0) { int maxHeight=0, numMaxHeight=1; for(int i=0; i<ar.length; i++) { if(maxHeight<ar[i]) { maxHeight=ar[i]; numMaxHeight=1; }else if(maxHeight==ar[i]) { numMaxHeight++; } } return numMaxHeight; } return 0;

Stelios10 + 2 comments just an optimization, even though in this case your code is fine: if you try an array with negatives, then you ll never get inside your if-statements. so the numMaxHeight will never change, so you dont really compute it in such cases. so this solution for an array with negatives, where the max negative appears more than once, will fail. eg [-1, -1]

proposed solution: set numMaxHeight = 0 on initialization

shashank_sm + 0 comments [deleted]sirmaridvan + 0 comments Can a birthday cake candle have a negative length?

shrikanth_n23 + 0 comments You can simplify it like this:

int max=ar[0]; int count=0; for(int i=0;imax){ max=ar[i]; count = 1; //Reinitialize count if you found a new max }

`else if(ar[i]==max){ count++; }`

} return count;

I this case you are traversing the vector only once.

pkarif4249816 + 0 comments [deleted]pkarif4249816 + 0 comments [deleted]soumabratabhatt1 + 0 comments i did the same thing.But it is showing me 4 test cases failed.

jord_fumar + 3 comments Be aware of time complexity. In my testcase 4, n was 10000. If you use a sorting algorithm with n^2, you will get a runtime error.

The way I structured my code is:

- Sort the array from min to max (quickSort)
- Parse from the very end of the array and iterate count++.
- When your values are no longer identical, stop.

jagmeetsingh + 5 comments I tried this

static int birthdayCakeCandles(int[] a) { Arrays.sort(a); //double pivot QuicKSort int count = 0; int i = a.length - 1; int tallest = a[i]; while (a[i--] == tallest) { count++; } return count; }

It is failing the test case

100000 followed by 100000 times 9999999 (as height of candles(array values)).

x_ireesh_x + 0 comments Pass all Testcases..

`static int birthdayCakeCandles(int[] ar) { Arrays.sort(ar); int result = 1; int decriment = 2; while((decriment <= ar.length) && (ar[ar.length-1] == ar[ar.length-decriment])){ result++; decriment++; } return result; }`

rishavtandon93 + 1 comment Try This

static int birthdayCakeCandles(int[] ar) {

`int count =0; Arrays.sort(ar); int maxHeight = ar[(ar.length)-1]; for(int i=0;i<ar.length;i++) { if(ar[i]==maxHeight) { count++; } } return count; }`

Kanahaiya + 1 comment Hi,

Your solution is good but it will take O(nlogn) time due to sorting which can be optimized to O(n)

Here is the video explanation of my solution in O(n) time -

Any comments and feedback will be appreciated.

wdodman + 0 comments Thanks for that. I worked out a solution where I do it in O(n) time. Posted on your video.

Amit_Sharma + 0 comments need to add one more check in while condition for all the array elements with same value

while ( i > -1 && a[i--] == tallest ) { count++; }

dpkcareergreatn1 + 0 comments Count should be initialized to 1 as there is atleast one tallest. In this case, if the frequency of largest element is 0, count would return 0 which is an error

bertgayus + 0 comments if you use quicksort u already have O(nlogn) which is worse than just iteratring through the array and saving the highest value and then just iterate a second time incrementing a counter everytime the value is similar to the saaved one. then complexity is O(2n) = O(n). With n = 100 you would have ~ 600 steps(n*logn = 100 * 6 = 600) with your solution and just 200 steps with mine

matthew_zilkie + 0 comments `Did you try using c++ std::sort(ar.begin(), ar.end()); ? I did and it worked flawlessly. int birthdayCakeCandles(int n, vector<int> ar) { // Complete this function sort(ar.begin(), ar.end()); int max = ar[ar.size() -1]; int count = 0; for(auto num : ar) { if(num == max) ++count; } return count;`

}

luckysam09 + 0 comments ar[i]-max==0 in second if worked for me

generalom1234 + 0 comments sandeep did u use unsigned long or any other data type which allows you to take in large amounts of data?

r_umans + 1 comment Since height of the candle is always at least 1, you can safely assume max = 0; Then loop all at once, you dont need a double loop. (Java syntax)

If(max < ar[i] ) { max = ar[i]; count =1; } else if (max==ar[i]) count++;

x_ireesh_x + 1 comment [deleted]x_ireesh_x + 1 comment [deleted]x_ireesh_x + 0 comments [deleted]

Anoop_SS + 0 comments You don't need the second loop. Checking of equal can be done in the else of

`if(ar[i] > max)`

matthew_zilkie + 0 comments [deleted]mercia_a + 0 comments thank you!

josephawilson86 + 0 comments Ask yourself a few questions:

- What do I need to return?

-The number of highest candles

- How would I get that number?

-I need to know what the highest candle is.

-I need to know how many of them there are.

- How would I know which is the highest candle?

-Simple comparison should work for knowing what the highest is. Just store it in a var and reset when I find one that's bigger.

- How would I track how many of they there are?

-Store the quantity in a var, increment it whenever I find one of the Highest candles and reset it each time I find a new highest candle.

wdodman + 0 comments ar.sort(); ar.reverse(); let m = 0; let k = ar[0]; while (parseInt(ar[m]) === parseInt(k)){ m++; } return m; }

passes 8 of 9.

qu4ku + 0 comments i'm not into c++, but this looks savage :)

trungskigoldberg + 1 comment Can you explain more about the complicated, savage version of that ternery statement? I really want to know this nifty code!

apghr + 15 comments while(std::cin >> n) max < n ? c = !!(max = n) : c += max == n;

can be translated as:

while(std::cin >> n){ // for each candle n check: if(max < n) { // does n set a new record in height? max = n; // if that's so, then n is the new max height c = 1; // and the counter c must be set to 1 again. "!!" is a cheap trick to convert any value different from 0 into 1 } else { // otherwise check if the new candle is as tall as max if (max == n) c++; // in that case, add 1 to counter (otherwise add 0) } }

arpita414 + 0 comments Too good

oswald200801 + 0 comments Nice one !!

aishwarya217 + 0 comments Good!

adityabcs93 + 0 comments nice one

lehieuminh231 + 0 comments nice. thank you

tarsum + 0 comments Well I came up with similar algorithm, so thumbs up. Also seems like solution in editorial goes though array twice, and this goes only once.

Vishwas92 + 0 comments hats off..

ichidan + 2 comments Nice one. I arrived at same algo in C, minus the one liner ternary. Looks neat, I like it. Although I'd be curious if there is not a small performance loss of doing:

c = !!(expr);

vs

(expr); c = 1;

the former may require additional conditional logic depending on architecture (for instance x86 - http://riffwiki.com/MOV_(x86_instruction) - the MOV instruction doesn't affect ZeroFlag, so I'd guess CPU would have to evaluate whether your expr results in a non-zero value. It's obvious to us as we can see the wider context of the algorithm, but not the CPU)

kurian_benoy + 0 comments thanks

viigihabe + 0 comments It is not CPU that analyses your c++, the compiler does. CPU doesn't "thin" but compiler does. It is really pointless to "optimize" your code this way because compiler is required to emit assembly that does what is ment but in which order and through which instructions, it is not specified. You better belive it does good job. You express c++ although it is slower than ++c: there is no way the compiler would use slower version if it doesn't afect the program flow. With no optimization flags may be.

lakshay91dutt + 0 comments [deleted]rahulsahu_blog + 0 comments This is brilliant!

gharibakhamis + 0 comments nice why didn't i think of this sooner

parvpareek + 0 comments TYSM!! Helped me a lot..

sabahat_usman_su + 0 comments I did the same thing but my code fails for some tests :O

jagmeetsingh + 0 comments I tried same in java. It worked! Thanks (:

int temp, max = 0, result = 0, n; for (int i = 0; i < arCount; i++) { n = scanner.nextInt(); temp = (max < n) ? (result = ((max = n) >= 0) ? 1 : 1) : (result += (n == max) ? 1 : 0); }

Ray1984 + 0 comments Very nice -- thanks for nudging me to think about it as a streaming algorithm :-)

colonel_bishop + 0 comments It's cool! Thanks!

ScienceD + 1 comment I dont understand how cin.ignore(); works... And how you can feed input into loop condition...

thermosphere453 + 0 comments cin.ignore() ignores the input of number of candles as its not needed in his algorithm and the input in loop works as long as the input isnt 0 or null, while loop works for any number in the test condition.

kachi_kinjal + 1 comment can u give the solution for c programming.

oswald200801 + 0 comments int main(){ int n; scanf("%d",&n); int *height = malloc(sizeof(int) * n); int max=height[0]; int count=0; for(int height_i = 0; height_i < n; height_i++){ scanf("%d",&height[height_i]); } for(int i=1; imax){ max=height[i]; } } for(int k=0; k

unicpawan + 8 comments can u please tell me why this code is not able to pass all the test case

// the code goes here..

int main(){ int n,i,max=0,frequency=0;

int

*ar =(int*) malloc(sizeof(int) * n);`scanf("%d", &n); for( i = 0; i < n; i++){ scanf("%d",&ar[i]); } for(i=0;i<n;i++){ if(ar[i]>max){ max=ar[i]; frequency=1; } else if(ar[i]==max){ frequency++; } } printf("%d",frequency); return 0;`

}

bharat_reddy18 + 0 comments # include

# include

# include

# include

# include

# include

# include

int birthdayCakeCandles(int n,int a[]) { long long int i,max=0,d=0; for(i=0;imax) { d=1; max=a[i]; } else if(a[i]==max) { d++; } } return d;

}

int main() { int n; scanf("%i", &n); int *ar = malloc(sizeof(int) * n); for(int ar_i = 0; ar_i < n; ar_i++){ scanf("%i",&ar[ar_i]); } int result = birthdayCakeCandles(n,ar); printf("%d\n", result); return 0; }

kuppesh_ds + 0 comments Return frequency to calling function instead of printig here.

vishalgwalani6 + 0 comments if you have case like 20,40,90,90,90 so you see according to your code in max variable value will 20 and frequency will be 1 and after the loop ends your result will be 4 instead it should be 3

shac_bandagi + 0 comments your else if part should be in for loop and in if statement remove that frequency set otherwise max number counted twice.

anurag0430 + 0 comments your are returning count of candles of same height. We have to return the number of candle he/she can blow out.

gaurav_877 + 0 comments you havent calculated the final max value and processed it before hand for comparision

maheshm121 + 0 comments what is max before entering the for loop??

gjaiswal108 + 0 comments because you have allocated memory to pointer ar using malloc function before taking the value of n from user. you should first take input n from user and then allocate memory to the pointer, i.e. first use scanf("%d",&n); then write int

*ar=(int*)malloc(sizeof(int)*n);hope, you understand.

kmschaal902 + 0 comments compact indeed, great job!

andrew_hedy77 + 4 comments Yeah, yours is way cleaner than mine

int birthdayCakeCandles(int n, vector <int> ar) { int count = 1; sort(ar.begin(), ar.end()); reverse(ar.begin(), ar.end()); for (int i = 0; i < n; i++){ if (ar[i] == ar[i+1]){ count++; } else break; } return count; }

amitsoni90 + 0 comments Why we need vector here?

cse_115 + 0 comments good solution

wem18 + 1 comment Solid solution. Wouldn't it be more efficient to do a for loop such as

//call sort //set int max = ar[n] for(int i = n; i>0; i++) { if(ar[i]==max) { count++; } else{ break; } return count; }

So you can avoid calling both sort and reverse? Not trying to correct you, genuine question

abhi69sindh + 0 comments it will not pass all the testcases

3001pratap + 0 comments [deleted]

shantanu_knight + 0 comments Great one

chandu007 + 0 comments awesome

karthikeyan90422 + 0 comments What is the use of cin.ignore() please tell me

lyj1186669164 + 0 comments That's so nice.Thanks

VIDYARANIGIDDE + 0 comments what is the role of cin.ignore() ?? what if we do not write that line?

cu_16bcs2416 + 0 comments wao! stupendous code!

benaffleks + 0 comments Can someone explain to me :

max < n ? c = !!(max = n) : c += max == n;

breakbadsp + 4 comments bro use python3 :

def birthdayCakeCandles(ar): return ar.count(max(ar))

No looping, no veriables, no mess

nsuniln1 + 0 comments [deleted]overwhelm + 0 comments wow this is crazy, thank you

lampladam1 + 0 comments i did the same. python is so useful when it comes to counting the number of occurences

dondorian + 0 comments No looping?

So, how were "max" and "count" calculated?

ilya_zarembsky + 0 comments Cute

Kanahaiya + 0 comments ## 100 % working code with video explanation -- All Test Case Passed..!!

## Here is the video explanation of my solution -

and you can find most of the hackerrank solutions with video explaination here-

https://github.com/Java-aid/Hackerrank-Solutions

and many more needs to be addeed.

Regards,

Kanahaiya Gupta

Git Hub URL | https://github.com/Java-aid/

LIKE US | https://www.facebook.com/javaaid/

SUBSCRIBE US | https://www.youtube.com/c/JavaAidTutorials

TELEGRAM LINK| http://t.me/javaaid

gadarsh555 + 1 comment can you explain it's process of working ?

Kanahaiya + 0 comments You can go through this tutorial-

Here is the video explanation of my solution -

ryanfehr18 + 14 comments A small Java solution in O(n) time with O(1) space:

//Java 8 /* Initial Thoughts: We can keep a running max and update it if we find something larger, if we find something smaller we just keep looking and if we find something equal then we increment a counter variable Time Complexity: O(n) //We must check the height of every candle Space Complexity: O(1) //We only store a max and a frequency */ import java.io.*; import java.util.*; import java.text.*; import java.math.*; import java.util.regex.*; public class Solution { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); int tallest = 0; int frequency = 0; for(int i=0; i < n; i++){ int height = in.nextInt(); if(height > tallest){ tallest = height; frequency = 1; } else if(height == tallest) frequency++; } System.out.println(frequency); } }

You can find more HackerRank solutions like this here

Dsmeenakshi + 1 comment if height is less than tallest means...wat wil happen

ryanfehr18 + 1 comment As mentioned above:

/* if we find something smaller we just keep looking */

Basically, we don't care about candles < tallest

Dsmeenakshi + 0 comments thank you dude

wyrlvillazorda + 0 comments it's great..thank you!

randy_evered + 1 comment `int max = 0; for (int v : a) if (v > max) max = v; int count = 0; for (int v : a) if (v >= max) count++; return count;`

sntz1 + 0 comments you can avoid doing two for loops by doing something along the lines of:

int max = 0; int count = 0; for (int v : a) { if (v > max) {max = v; count = 1;} else if (v == max) count++; } return count;

You can avoid iterating over the collection twice

SupreethMC + 0 comments Nice approch !

borisaltynnik + 2 comments Why not to use first array element like initial value of max ? Does it make any sense ?

static int birthdayCakeCandles(int n, int[] ar) { int max=ar[0]; int num=1; for (int i=1;i<n;i++){ if (ar[i]>max){ max=ar[i]; num=1; } else if (ar[i]==max) num++; } return num; }

iamkarthik49 + 0 comments Yeah ! I did the same thing but complicated it... Your's looks clean and clear thanks for the solution... :) .

santunu23 + 1 comment Nice one thanks for sharing,actually I have been working on this solution for a hour,finaly it work thanks dude.

Coder_Zuki + 0 comments No Probs Dude

kvnfrederiksen0 + 0 comments HAH! I did the exact same thing. Nice.

int n = in.nextInt(); int j = 0; int max = 0; for(int i = 0; i < n; i++){ int x = in.nextInt(); if(x > max){ j = 1; max = x; } else if(x == max) j++; } System.out.print(j);

shantanu_bugadi + 0 comments simply wow.. what i got by this code is , try to do most of it simultaneously....

3001pratap + 1 comment static int birthdayCakeCandles(int n, int[] ar) { int count=0; Arrays.sort(ar); int tallest = ar[n-1]; for(int i=0; i<n; i++) { if(ar[i] == tallest) count++; } return count; }

fhrazib + 0 comments I think this can be improved a little bit using a break. We don't need to traverse all the array to get the total count when the array is sorted (here in ascending order) -

`Arrays.sort(a); int tallestOne = a[n-1]; int count = 1; for(int i=n-2; i>=0; i--){ if(a[i]==tallestOne) { count++; } else break; }`

hollybush + 0 comments Amazing solution mate!

zakiralig184 + 0 comments Cool!

pep1439 + 0 comments use

tallest = Integer.MIN_VALUE

instead, for general use.

stephen_kalletta + 0 comments very clean. I was sorting it and grabbing the last values, but I like this much better. thanks for sharing

Coder_Zuki + 2 comments Did This...! Seems Simple right?

static int birthdayCakeCandles(int n, int[] ar) { // Complete this function int size=ar.length; int tall=ar[0]; int count=0;

`for(int i=0 ; i<size ; i++) { if(ar[i]>tall) { tall=ar[i]; } } for(int j=0;j<size;j++) { if(ar[j]==tall) count++; } return count; }`

j_zambre66 + 0 comments [deleted]nikhilgarakapat1 + 0 comments Give count=1;

j_zambre66 + 0 comments Can be done it like this.

int max = 0, count = 1; for (int v : ar) { if (v == max) count++; if (v > max) max = v; } return count;

ATVex + 10 comments Counting the tallest candles.

n = int(input().strip()) height = [int(height_temp) for height_temp in input().strip().split(' ')] print(height.count(max(height)))

abhishek106 + 1 comment python is the best!

rudra_utpal + 1 comment Any problem with Java @abhishek106

import java.util.*; public class Solution { public static void main(String[] args) { Scanner scan=new Scanner(System.in); int n=scan.nextInt(); ArrayList<Integer> al=new ArrayList<Integer>(); for(int i=0;i<n;i++) al.add(scan.nextInt()); System.out.println(Collections.frequency(al,Collections.max(al,null))); } }

aaron_gomez1 + 1 comment While this works, you loop through the complete collection of values 3 times. First while reading it in the scanner. Second while scanning for the max value in the collection after reading it in and third to count the number of times it was found.

fernando_becerr1 + 1 comment anyway the time complexity is O(n+n+n) = O(n)

riaan_rvr + 1 comment I'm not too familiar with the BigO notation, so an honest question how does it become n+n+n shouldn't it be 3n rather as you are doing full loops over all elements?

hua_duy + 0 comments In BigOh notation, I believe they drop the constants in front of n because exponents matter so much more that the constants are negligible.

egrodo1 + 0 comments [deleted]egrodo1 + 3 comments Why do that instead of just?

n = int(raw_input().strip()) candles = map(int,raw_input().strip().split(' ')) print candles.count(max(candles))

randy_evered + 0 comments Wow, egrodo1, Python for the win!

Modelmat + 0 comments I basically did the same thing!

pheepia7788 + 0 comments nice code! as I am a beginner, I think very long and messy code.... lol

Dulguun_Otgon + 0 comments [deleted]helderIO + 0 comments [deleted]dandaraviteja + 2 comments n = int(input().strip()) ar = (list(map(int, input().strip().split(' ')))) print(ar.count(max(ar)))

paccel22 + 0 comments Thank you! I hadn't realized Python had a count method for lists that basically reduces the problem to 1 step.

Anubhav_singh + 1 comment what is the code of "count" function?? bcos when I am using loop instead of count fuction, its taking too much time to run. pls help??

ARXINO + 0 comments I am using loop but it is the same thing with ar.count(max(ar))

def birthdayCakeCandles(n, ar): max_height=0 double=0 for x in range(n): if ar[x]>max_height: max_height=ar[x] for y in range(n): if ar[y] == max_height: double+=1 return double

sehan2 + 3 comments from collections import * def birthdayCakeCandles(n, ar): res = Counter(ar) return res.most_common()[0][1]

croqaz + 0 comments Exactly like I did! Nice!

rowlandoti + 1 comment This is not a correct solution but I do not know why it is passing. You should:

- Get the max element
- Return or print its count/frequency.

pawelwiszniewski + 0 comments In some test cases, the highest (max) element is the one most common - like in example case, where 3 is the most common element. It also passes some test cases. The correct solution is the one with Counter.

vinasatinfo + 0 comments just simple

`return Counter(ar).most_common()[0][1]`

actually :-)

Spiznak + 2 comments My solution finishd in about half the time, I would assume because I'm looping through it only once. Depends on whether you want a quick and dirty solution (mine) or one that's more Pythonic (in your case, can be more difficult to read):

n = input() arr = input().split() theMax, count = 0, 0 for x in arr: x = int(x) if x > theMax: theMax = x count = 1 elif x == theMax: count += 1 print(count)

icehongssii + 0 comments data=[10,3,333,333,333,0,13] tmp=data[0] #max data tmp2=0 #max data counter for i in range(len(data)-1): for j in range(i+1,len(data)): if(tmp<=data[j]): tmp=data[j] for k in range(len(data)): if(data[k]==tmp): tmp2+=1 print(tmp2)

this was my code. to get max_height, i use the loop twice. so it didn't work. but like you said, its working with single loop! thanks and it is so amazing that you used single looop... never imagined it

gb3010 + 0 comments I use max function in list. 7 out of 8 test cases work. I am not sure what's wrong with my code. Can you please have a look ?

n1=input().strip() # Input age value b1=input().strip().split() # Input list of candle heights def birthdayCakeCandles(n,b): c=0 z=max(b) for i in b: if i == z: c += 1 return(c) y=birthdayCakeCandles(n1,b1) print(y)

nicolasmontoya + 2 comments similar:

input() arr = list(map(int, input().split())) print(arr.count(max(arr)))

pawelwiszniewski + 1 comment EDIT: My mistake, i've missread the description :(. So the rest of the comment is invalid.

This doesn't work. It only counts how many times the highest element from the list (max(arr)) is in the list. In some test cases it works. In some it doesn't -> it's not a correct solution

brevnovak + 1 comment i don't understand. it's what we are looking for, is it not?? ;)

pawelwiszniewski + 0 comments You're right, I've missread the description.

wanwanzhang + 1 comment Hi I also use the same way to count in Python print(arr.count(max(arr))), but the result is always 2, none, which show me the worng answer. I do not know why it show me (2, none) instead of just 2.

RJ_29 + 0 comments Try to return the value from the function instead of printing.

return(ar.count(max(ar)))

EeXoR_Daniel_Ng + 0 comments python FTW:>

jeffmagill + 2 comments C# solution...

int tallest = height.Max(); int count = height.Count(c => c == tallest); Console.WriteLine(count);

indyHarcourt + 3 comments Or

int result = ar.Where(i => i == ar.Max()).Count();

unSatisfied + 0 comments That's O(n^2) since you're finding the max value on each iteration of the where statement. The best solution would be to use a single for/foreach loop, but jeffmagill's solution (looping through the list twice) is still much more efficient than this.

shatrudhankr + 1 comment [deleted]laysa_uchoa + 0 comments best comment

daeden + 0 comments I don't think you deserver a downvote, its solution i came up with the returned failed tests (tests timed out) for me.

I wish it was explained where other than comments why this wasn't a valid result.

leonardomiceli87 + 0 comments C# other way

var max = ar.Max(); return Array.FindAll(ar, s => s == max).Length;

Dalenguyen + 8 comments Nice to have modern JavaScript:

function birthdayCakeCandles(n, ar) { // Complete this function var max = Math.max(...ar); var result = ar.filter(c => c === max); return result.length; }

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

aJaxs + 0 comments è¿™ä¸ªfilterå¾ˆæœºæ™º

sameer_jain1 + 0 comments 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

netris + 0 comments [deleted]netris + 1 comment 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;

}brecht_pynoo + 0 comments 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

`function birthdayCakeCandles(ar) { let max = 0; return ar.reduce( (count, i) => i === max ? count + 1 : i > max ? (max = i) && 1 : count, 0 ); }`

n_haque + 0 comments Oh filter and result.length is so much simpler! Mine was a little longer

function birthdayCakeCandles(ar) { let tallest = Math.max(...ar) let candleCount = 0 ar.forEach((candle) => candle === tallest ? candleCount++ : null) return candleCount }

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

josiah_mokobo + 1 comment function birthdayCakeCandles(ar) { return ar.filter(height => height === Math.max(...ar)).length }

josiah_mokobo + 0 comments You can filter out the max numbers from the array, and return its occurrance

bryank + 0 comments You can make it shorter with a bit of chaining.

function birthdayCakeCandles(ar) { const max = Math.max(...ar); return ar.filter(c => c === max).length; }

leo_kamwathi + 0 comments HINT: If you get a timeout. Avoid using complex methods. Keep it simple.

Elvis2597 + 3 comments def birthdayCakeCandles(n, ar): return max(Counter(ar).items())[1]

saurabh_kumar3 + 1 comment I used this:===>

TreeMap mapCandleCount=new TreeMap(); for(int i=0; i } int first = mapCandleCount.lastEntry().getValue(); return first;

bendjoudifirst + 0 comments [deleted]

arsenij_smth + 1 comment A bit different one:

def birthdayCakeCandles(n, ar): return ar.count(max(ar))

pawelwiszniewski + 0 comments [deleted]

owenklaiss + 0 comments [deleted]

marinskiy + 1 comment Here is

**Python 3**solution from my HackerrankPractice repository:n = int(input()) ar = list(map(int, input().split())) print(ar.count(max(ar)))

Feel free to ask if you have any questions :)

voodoorrj1990 + 0 comments [deleted]

shangardezi + 1 comment Two ruby solutions:

def birthdayCakeCandles(ar) height = 0 ar.each { |x| height = x if x > height } ar.select { |x| x == height }.count end

def birthdayCakeCandles(ar) ar.select { |x| x == ar.max }.count end

niiccolas + 0 comments Hey fellow Rubyist,

The second approach is syntactically correct but will fail to pass the hairier of test cases on the grounds of "

**â€¦timeout**". Rightly so: with Test Case #4, an array of 100000 * 7 digits long integers, this implementation will take a whopping**Â±19 seconds**to return an answer!This was my first intuitive implementation but maybe calling the

`.max`

method on each & every enumeration of the`.select`

method isn't the smartest choice :-)A middle way between the dumb oneliner and your first solution:

def birthdayCakeCandles(ar) tallest_candle = ar.max ar.select { |height| height == tallest_candle }.count end

The

*smart*oneliner:def birthdayCakeCandles(ar) ar.count(ar.max) end

And

`Benchmark`

module says it's fastest to be smart:user system total real dumb 19.362941 0.053301 19.416242 ( 19.484988) each 0.011273 0.000056 0.011329 ( 0.011371) midway 0.005402 0.000021 0.005423 ( 0.005426) smart 0.000847 0.000001 0.000848 ( 0.000847)

Sort 1437 Discussions, By:

Please Login in order to post a comment