C# - handles int.MaxValue should it appear in numbers array


  • 1

    This problem is simple but a little tricky to handle edge cases without a ton of if statements. Anyhow, my idea was to use a helper function to find the max below a given max, I call this "NextMax". Use it to find first max, use that to find second max and use that to find third max, still O(n) solution. When no next max is found my NextMax function returns the max and so to handle the edge cases I check that the NextMax is less than previous max, else this is the condition where we should return the max.

    If there is a more elegant solution I'd like to see it! Thanks.

    public int ThirdMax(int[] nums) {
        int max = NextMax(nums, int.MaxValue);    
        int max2 = NextMax(nums, max);
        if (max2 == max) return max;
        else
        {
            int max3 = NextMax(nums, max2);
            if (max3 == max2) return max;
            else return max3;
        }
    }
    
    public int NextMax(int[] nums, int max)
    {
        int nextMax = 0;
        bool any = false;
        for (int i = 0; i < nums.Length; i++)
        {
            if (nums[i] < max)
            {
                if (any == false)
                {
                    nextMax = nums[i];
                    any = true;
                }
                else if (nums[i] > nextMax)
                {
                    nextMax = nums[i];
                }
            }
        }
        
        return any ? nextMax : max;
    }

Log in to reply
 

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