# Third Max Number (4ms - Java)

• The last 3 test cases (which includes Integer.MIN_VALUE) are specially handled

``````public class Solution {
public int thirdMax(int[] nums) {
if(nums.length == 0){
return -1;
}
else if(nums.length == 1){
return nums[0];
}
else if(nums.length == 2){
return Math.max(nums[0],nums[1]);
}
else {
int first   = Integer.MIN_VALUE;
int second  = Integer.MIN_VALUE;
int third   = Integer.MIN_VALUE;
int count = 0;
for(int i = 0; i < nums.length; i++){
if(first < nums[i]){
count++;
third  = second;
second = first;
first = nums[i];
}
else if(second < nums[i] && first > nums[i]){
count++;
third = second;
second = nums[i];
}
else if(third < nums[i] && second > nums[i] && first > nums[i]){
count++;
third = nums[i];
}
}

if(count >= 3)
return third;
else if((nums[0] == Integer.MIN_VALUE && nums[1] != nums[2] )||
(nums[1] == Integer.MIN_VALUE && nums[0] != nums[2] )||
(nums[2] == Integer.MIN_VALUE && nums[0] != nums[1] )){
return third;
}
else {
return first;
}

}
}
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.