## Birthday Cake Candles

apghr + 16 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

- YM
Yakubk_98 + 1 comment 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 + 1 comment this code was working on some test case but not all please help me

- VG
vaishaligarg2012 + 1 comment /*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;

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

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 + 14 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) } }

- AH
arpita414 + 0 comments Too good

- O
oswald200801 + 0 comments Nice one !!

aishwarya217 + 0 comments Good!

adityabcs93 + 0 comments nice one

- LM
lehieuminh231 + 0 comments nice. thank you

- B
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.

- VL
Vishwas92 + 0 comments hats off..

- IM
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)

- KB
kurian_benoy + 0 comments thanks

- KS
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!

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

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

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

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

make9chaos + 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...

- KA
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.

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

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

}

- BR
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.

- VG
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

- MB
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.

- KS
kmschaal902 + 0 comments compact indeed, great job!

- AH
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; }

- AS
amitsoni90 + 0 comments Why we need vector here?

cse_115 + 0 comments good solution

- WM
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

- 3
3001pratap + 0 comments [deleted]

- SS
shantanu_knight + 0 comments Great one

chandu007 + 0 comments awesome

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

- LY
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?

- C
cu_16bcs2416 + 0 comments wao! stupendous code!

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

- DS
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

- DS
Dsmeenakshi + 0 comments thank you dude

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

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

- M
mrnubnub + 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 !

- BA
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.

- VM
Coder_Zuki + 0 comments No Probs Dude

- KF
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....

- 3
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; }

- FH
razib_fh + 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!

- ZA
zakiralig184 + 0 comments Cool!

- AK
pep1439 + 0 comments use

tallest = Integer.MIN_VALUE

instead, for general use.

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

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

- A
ATVex + 9 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))); } }

- AG
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)

- RV
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?

- H
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 + 2 comments Why do that instead of just?

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

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

Modelmat + 0 comments I basically did the same thing!

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

- JH
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

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

- CC
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.

- MP
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)

- JL
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)

- N
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

- BB
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.

- WZ
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.

- JM
jeffmagill + 1 comment C# solution...

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

- JH
indyHarcourt + 3 comments Or

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

- U
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]- LU
laysa_uchoa + 0 comments best comment

- LV
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.

- AS
Elvis25 + 2 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;

- BD
bendjoudifirst + 0 comments [deleted]

- AP
arsenij_smth + 1 comment A bit different one:

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

pawelwiszniewski + 0 comments [deleted]

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

rylaco + 1 comment int main(){ int n; cin >> n; long int height[n], max = 0, count = 0; for(int i = 0; i < n; i++){ cin >> height[i]; if(height[i] > max) max = height[i]; } for(int i = 0; i < n; i++){ if(height[i] == max) count++; } cout << count; return 0; }

- MC
bart4282819 + 1 comment Do you happen to know why max and count have to be long? Had everything correct except that.

rylaco + 1 comment No idea, I probably did that on a hunch. I liked the code of python guy below my post. There is no need for second for loop. Anyway, the time complexities are linear for both.

Sumukha1496 + 0 comments Yeah. You can do it with a single loop.

disabajn + 0 comments Python:

return ar.count(max(ar))

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

- AV
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.

Sort 935 Discussions, By:

Please Login in order to post a comment