Interview Question & Answer – 8

By | October 8, 2018

Question

You are in charge of the cake for your niece’s birthday and have decided the cake will have one candle for each year of her total age. When she blows out the candles, she’ll only be able to blow out the tallest ones. Your task is to find out how many candles she can successfully blow out.

For example, if your niece is turning 4 years old, and the cake will have 4 candles of height
4, 4, 1, 3, she will be able to blow out 2 candles successfully, since the tallest candles are of height 4 and there are such candles.You are in charge of the cake for your niece’s birthday and have decided the cake will have one candle for each year of her total age. When she blows out the candles, she’ll only be able to blow out the tallest ones. Your task is to find out how many candles she can successfully blow out.

Output Format

Print the number of candles that can be blown out on a new line.

Sample Input

4
3 2 1 3

Sample Output

2

Solution

static int birthdayCakeCandles(int[] ar) {
    int countTallest = 0;
    int tallest = 0, prevTallest = -1;
    int len = ar.length;
    for (int i = 0; i < len; i++) {
        if (tallest <= ar[i]) {
            tallest = ar[i];
            if(prevTallest == tallest) {
                countTallest++;
            }else {
                countTallest = 1;
            }
            prevTallest = tallest;
        }
    }
    return countTallest;
}

Leave a Reply

Your email address will not be published. Required fields are marked *