Follow the hints! - Part 5

In this problem the hints are very useful: first, make a hash table (or set) to access the elements of the array quickly. Second, try every element as if it was the outlier, do some math manipulation to check if that element is a valid candidate, and if so keep track of the max. Notice that you achieve linearity with multiple 1-passes. Code is down below, cheers, ACC.


3371. Identify the Largest Outlier in an Array
Medium

You are given an integer array nums. This array contains n elements, where exactly n - 2 elements are special numbers. One of the remaining two elements is the sum of these special numbers, and the other is an outlier.

An outlier is defined as a number that is neither one of the original special numbers nor the element representing the sum of those numbers.

Note that special numbers, the sum element, and the outlier must have distinct indices, but may share the same value.

Return the largest potential outlier in nums.

 

Example 1:

Input: nums = [2,3,5,10]

Output: 10

Explanation:

The special numbers could be 2 and 3, thus making their sum 5 and the outlier 10.

Example 2:

Input: nums = [-2,-1,-3,-6,4]

Output: 4

Explanation:

The special numbers could be -2, -1, and -3, thus making their sum -6 and the outlier 4.

Example 3:

Input: nums = [1,1,1,1,1,5,5]

Output: 5

Explanation:

The special numbers could be 1, 1, 1, 1, and 1, thus making their sum 5 and the other 5 as the outlier.

 

Constraints:

  • 3 <= nums.length <= 105
  • -1000 <= nums[i] <= 1000
  • The input is generated such that at least one potential outlier exists in nums.
Accepted
10,848
Submissions
47,865


public int GetLargestOutlier(int[] nums)
{
    Hashtable vals = new Hashtable();
    foreach (int n in nums)
    {
        if (!vals.Contains(n)) vals.Add(n, 0);
        vals[n] = (int)vals[n] + 1;
    }
    int sum = nums.Sum();

    int retVal = -10000;
    foreach (int n in nums)
    {
        int outlier = n;
        if ((sum - outlier) % 2 == 0 && vals.Contains((sum - outlier) / 2))
        {
            int candidate = (sum - outlier) / 2;
            if (candidate != outlier || (int)vals[candidate] > 1)
                retVal = Math.Max(retVal, outlier);
        }
    }

    return retVal;
}


Comments

Popular posts from this blog

Golang vs. C#: performance characteristics (simple case study)

Claude vs ChatGPT: A Coder's Perspective on LLM Performance

The Power Sum, a recursive problem by HackerRank