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
?