Reputation: 17655
arr
is an int array of 5 elements only.
We need to calculate sum of only 4 smallest minimum numbers and sum of 4 largest maximum mumbers from these 5 elements.
example: int[] arr= {5,2,3,4,1}
In this array,
4 smallest minimum numbers are: 1,2,3,4
so totalMin = 1 + 2 + 3 + 4 = 10
Largest 4 Maximum numbers are: 5,4,3,2
so totalMax = 14
So output will be : 10, 14
.
My below code is working correctly for 40% cases, but not working for 60% cases.
I sorted Array first .. so that always smallest numbers will be: arr[0], arr[1], arr[2], arr[3]
and MAX will be arr[4], arr[3], arr[2], arr[1]
HackerRank showing that my this answer is wrong for some cases , but those are locked. I dont know those cases... I am also wondering what will be those cases?
Can anybody explain me? What wrong am doing here?
You can check more details of question here: https://www.hackerrank.com/challenges/mini-max-sum/problem
static void miniMaxSum(int[] arr)
{
Arrays.sort(arr);
Integer min=arr[0]+arr[1]+arr[2]+arr[3];
Integer Max=arr[4]+arr[3]+arr[2]+arr[1];
System.out.println(min+" "+Max);
}
Upvotes: 0
Views: 2233
Reputation: 17655
Yes. My mistake, was not converting int to long (64-bit Integer).Error was because of integer Overflow
static void miniMaxSum(int[] arr)
{
Arrays.sort(arr);
long min= (long)arr[0]+(long)arr[1]+(long)arr[2]+(long)arr[3];
long max= (long)arr[4]+(long)arr[3]+(long)arr[2]+(long)arr[1];
System.out .println(min+" "+max);
}
Upvotes: 0
Reputation: 311308
With the given constraints, the largest sum you can produce is 4 * 109, which overflows an integer. However, it fits nicely into a long
, so summing the values as long
s should do the trick:
long min = (long)arr[0] + (long)arr[1] + (long)arr[2] + (long)arr[3];
long max = (long)arr[4] + (long)arr[3] + (long)arr[2] + (long)arr[1];
Note, however, that this solution still has an O(nlog(n)) time complexity due to the sorting.
This can be improved to O(n) - in a single pass of the array you could get the sum, min and max of it, and then subtract the maximum from the sum to git the "min" value and the minimum from the sum to get the "max" value.
Using an IntStream
will do most of the heavy lifting for you:
IntSummaryStatistics stat = Arrays.stream(arr).summaryStatistics();
long min = stat.getSum() - stat.getMax();
long max = stat.getSum() - stat.getMin();
Upvotes: 6
Reputation: 91
long first = arr[0];
long second = arr[1];
long third = arr[2];
long fourth = arr[3];
long fifth = arr[4];
long min = first + second + third + fourth;
long Max = second + third + fourth + fifth;
Above will work, the reason being is input and result may exceed 32 bit so we have to use long and we have cast each value of long before doing the sum operation because, it may also exceed more than 32 bit
Upvotes: 1