Third Maximum Number

There’s a question on leetcode which i am unable to understand. Need Help

Hi @yashhanda028_2ac57e80580f4767
Please provide me statement of question and tell me what help do you need in that question from me

Given an integer array nums , return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number . This is the question and i tried and even searched for the soln but i am not able to understand it. Therefore it would be really helpful if u could do a dry run for me and explain the working. public int thirdMax(int[] nums) {
Arrays.sort(nums);
int count=1;
int max = nums[nums.length-1];
for(int i=nums.length-1;i>0;i–){
if(nums[i]!=nums[i-1])
count++;
if(count==3)
max=nums[i-1];
}
return max;
}

Here According to this code what we are doing is just sort our given array first and then we will be traversing the array in backward direction and side by side maintaing the count variable and once the count will become 3 we will be upadating the value in max and return that value. The if condition is here bcz in array we might occur duplicate elements also so to handle that case we use if condition here.
For example :-
Array = {1 , 1 , 3}
output = 3
Explanation :- The first maximum is 3, second maximum is 1, but there is no third maximum because we consider both the 1s as the second maximum here.

yeah but why are we traversing in the reverse direction…we have to tell the third distinct max from the 0th index right

We are traversing it from backward as we have sort our array so traversing from back will be easier for us to find the element and we have to find the 3rd distinct maximum element in whole array not from 0th index it is not necessary.

okay i get it… thanks

If I solved your doubt please mark the doubt as resolved and provide your feedback please.

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.