Best Solution | Best Explanation | Most Optimum |
Intuition\nif T is the total sum of all n elements in the array such that n-2 special elements have sum s ( one of remaining 2 elems) and o is the outlier.\n\nT
# Intuition\nif `T` is the total sum of all `n` elements in the array such that `n-2` special elements have sum `s` ( one of remaining 2 elems) and `o` is the outlier.\n\nThen `T = 2*S + O`......................(1)\n\nTherefore, `s = (T - O)/2`..............(2)\n\nSince we need to get the maximum value of outlier, by brute force we will check each element of the array to be the outlier, and get the corresponding value of `s` from it, now if the pertiuclar value of `s` does exist in the array, then it means that the corresponding element is an outlier, Therefore like this for each element we will check if it is valid outlier and then get the maximum outlier by comparision.\n\n## Edge Case\n[6,-31,50,-35,41,37,-42,13], wrongly considering 13 as largest outlier, but correct answer is -35.\n\nThere can be case where value `s` comes out to be same as outlier, `O`, from the formula (2), then if the frequency of outlier in array is 1, then we may wrongly consider an element to be a valid outlier.\nTherefore we also check the frequency of each element, when considering it as outlier, such that, if `s` comes out to be equal to `O`, then frequency of this current element being considered as outlier, must be greater than 1.\n\n\n\n\n# Code\n```java []\nclass Solution {\n    public int getLargestOutlier(int[] nums) {\n        int n = nums.length;\n        HashMap<Integer, Integer> map = new HashMap<>();\n\n        int sum = 0; \n\n        for(int i = 0; i < n; i++){\n            sum += nums[i];\n            map.put(nums[i], map.getOrDefault(nums[i], 0)+1);;\n        } \n\n        int mx = Integer.MIN_VALUE;\n\n        for(int i = 0; i < n; i++){\n\n            int s = (sum - nums[i]);\n\n            if(s % 2 == 0 && map.containsKey(s/2)){\n                if(s/2 != nums[i] || map.get(nums[i]) > 1){\n                    mx = Math.max(mx, nums[i]);\n                } \n            }\n        }\n\n        return mx;\n    }\n}\n```
['Java']