Birthday Cake Candles

Birthday Cake Candles

 

The question is inspired from hackerrank.

You are in charge of the cake for a child's birthday. You have decided the cake will have one candle for each year of their total age. They will only be able to blow out the tallest of the candles. Count how many candles are tallest. 

Ex:

array=[5,6,7,4,5,7]

The maximum height of the candle is 7 and their are 2 highest candles so the answer will be 2.

Explanation:

1.Find the maximum in the array

2.Find the count of the maximum

Code:

 
 static int birthdayCakeCandles(int[] ar) {
    
    if(ar.length==0)return 0;
    int n=ar.length;
    int candle=0;
    int max=-1;
    for(int i=0;i<n;i++)
    {
        max=Math.max(max,ar[i]);
    }

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

return candle;
    }
 
Analysis:
  • If you look into the asymptotic analysis , the time complexity will be O(n) 
  • where n is the number of elements in the array.
  • We traverse the n elements in the array 2 times thus it is 2*n but asymptotically it will be O(2) 
  • since we don't consider constants while dealing with higher values.
  • The space complexity will be O(n), since we are storing the n elements in the array.
 
 

Post a Comment

0 Comments