0

As far as I know, Integer is just a wrapper around int. So the maximum value that can be stored in both should be the same. Is this correct?

But while attempting to solve a HackerRank problem (details follow), the solution failed for some inputs while using Integer and succeeded for the same inputs while using int.

The HackerRank problem:

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. Example: candles = [4, 4, 1, 3]. The maximum height candles are 4 units high. There are 2 of them, so return 2.

My Solution that works for all inputs:

public static int birthdayCakeCandles(List<Integer> candles) {
    int maxElement = 0;
    Integer maxElementCount = 0;
    for(Integer element: candles) {
        if (element > maxElement) {
            maxElement = element;
            maxElementCount = 1;
        } else if (element == maxElement) {
            maxElementCount++;
        }
    }
    return maxElementCount;  
 }

The size of candles can be between 1 and 105. Values in candles can be between 1 and 107.

When maxElement is changed to Integer, the solution starts failing for some inputs. Since the variable in question is the maximum value and since (as per the question) its value can go up to 107, I wonder if int has the same max. value as Integer?

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
Ram
  • 865
  • 1
  • 8
  • 20
  • 5
    If `maxElement` was an `Integer`, the `==` would be comparing for reference equality between two wrappers. – Sweeper Apr 25 '23 at 12:17
  • Ahhh.... This makes a ton of sense. Thank you. Happy to accept your comment as an answer if posted as one. – Ram Apr 25 '23 at 12:19
  • There is no point in declaring the counter as `Integer`, just make that `int` too. – Andy Turner Apr 25 '23 at 14:08

0 Answers0