Hi I was solving a very basic problem on Hackerrank about determining Mini-Max Sum of all the values in an integer array. Basically given an array of 5 values like [1, 2, 3, 4, 5], the minimum sum will be 1+2+3+4 = 10 and maximum sum will be 2+3+4+5 = 14. Very simple question, but I am running into an issue with a certain large input values. Below are my solutions and their result.
//Input: 256741038 623958417 467905213 714532089 938071625
//Output: 2063136757 2744467344
Below is using inbuilt Sum() method.
static void Main(string[] args)
{
int[] arr = new int[5] {256741038,623958417,467905213,714532089,938071625};
Array.Sort(arr);
long arrSum = arr.Sum(); //System.OverflowException: 'Arithmetic operation resulted in an overflow.'
long minSum = arrSum - arr[arr.Length - 1];
long maxSum = arrSum - arr[0];
Console.WriteLine(minSum + " " + maxSum);
}
Below is using Aggregate extension method.
static void Main(string[] args)
{
int[] arr = new int[5] {256741038,623958417,467905213,714532089,938071625};
Array.Sort(arr);
long arrSum = arr.Aggregate((total, next) => total + next); // arrSum = -1293758914
long minSum = arrSum - arr[arr.Length - 1];
long maxSum = arrSum - arr[0];
Console.WriteLine(minSum + " " + maxSum);
}
Output: -2231830539 -1550499952
And if I use the regular foreach loop like below:
static void miniMaxSum(int[] arr)
{
Array.Sort(arr);
long arrSum = 0;
foreach (var value in arr)
{
arrSum += value;
}
long minSum = arrSum - arr[arr.Length - 1];
long maxSum = arrSum - arr[0];
Console.WriteLine(minSum + " " + maxSum);
}
The output is correct as expected i.e. 2063136757 2744467344
The OverflowException class description here says "An arithmetic operation produces a result that is outside the range of the data type returned by the operation". But the arrSum
value is within long
range so I am not able to figure out the issue. So not sure if I am missing anything or using the functions incorrectly but not able to understand this behavior.
Any detail is appreciated.