C++ Solution: Birthday Cake Candles HackerRank

Birthday Cake Candles

Hackerrank Easy Difficulty problem, authored by shashank21j. The max score is 10


Logic

  • Get the number of candles(array size)
  • Declare the array to store candles
  • Sort array in reverse 
  • Assign tallest candle to T for comparison
  • Set initial count to 1 for tallest candle
  • Check all candles for match
  • If match found increment counter
  • If match not found break the loop to save time
  • Print count


Code

#include <bits/stdc++.h>
using namespace std;

int main(){
   int n;                                // number of candles(array size)
   cin>>n;
   
   int a[n];                        //to store candles
   
   for(int i=0;i<n;i++){    
       cin>>a[i];
    }
   
   sort(a,a+n,greater<int>());            // sorting array in reverse 

   int t=a[0];                                        //assigning tallest candle to T for comparison
   int c=1;                                            // set initial count to 1 for tallest candle

   for(int i=1;i<n;i++){                        //checking all candles
       if(a[i]==t){                                    // if match found increase counter
           c++;
       }
       else{                                            //otherwise break the loop to save time
           break;
       }
   }
   cout<<c;                                        //print count

   return 0;
}

Post a Comment

0 Comments