# Birthday Cake Candles

# Birthday Cake Candles

apghr + 18 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 + 2 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 + 2 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 + 3 comments this code was working on some test case but not all please help me

vaishaligarg2012 + 2 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 + 0 comments 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;

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.

jord_fumar + 2 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 + 1 comment 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; }`

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

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

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]

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.

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;`

}

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

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 + 0 comments bro use python3 :

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

No looping, no veriables, no mess

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 + 1 comment 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]

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

EeXoR_Daniel_Ng + 0 comments python FTW:>

jeffmagill + 1 comment 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.

disabajn + 0 comments Python:

return ar.count(max(ar))

Dalenguyen + 2 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å¾ˆæœºæ™º

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]

berukblue + 0 comments Important note for folks attempting this in Go:

Do not use bufio.Scanner to read the input lines as the later test cases will consist of lines with >10000 numbers and lead to "token too long" errors. Use bufio.Reader instead.

Took me a while to figure this out as the later test cases don't show your output and bufio.Scanner is just simpler to use IMO

uniyal_guru + 1 comment my function is as follows:

static int birthdayCakeCandles(Integer n, Integer[] ar) { int count=0; List<Integer> cardsList =Arrays.asList(ar); Integer max=Collections.max(cardsList); for(int j=0;j<cardsList.size();j++) { if(cardsList.get(j)==max) { System.out.println("TMC"); count++; } else System.out.println("BCMK"); } return count; }

`but it checks the integer values only upto 127. can anyone help me out?. PS: I have attached the output of the program.`

abhishek2438 + 0 comments i have checked this code and there is a problem in if condition.If the occurence of maximum value is more than once then "if" condition is comparing the max value above 127 just once.

nakulmalhotra + 0 comments I am getting runtime error on testcase 6 and 7.What am I doing wrong ?

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

Sort 1114 Discussions, By:

Please Login in order to post a comment