Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
static void miniMaxSum(int[] arr) {
int summin=0;
int summax=0;
for (int i=0; i< 5; i++) {
for (int j=4; j>i; j--) {
if(arr[i]>arr[j]){
int c=arr[i];
arr[i]=arr[j];
arr[j]=c;
}
}
}
for (int i=0; i<4; i++) {
summin=summin+arr[i];
}
for (int i=1; i<5; i++) {
summax=summax+arr[i];
}
System.out.print(summin+" "+summax);
}
My code only works correctly enter image description here with 5/15 testcases. I want to sort the array and then calculate the result. The "min" result is correct, but the "max" result is a negative integer so it's wrong. I found the problem is caused by the last element after sorted. Using Netbeans, I calculated the sum of all element in the array. After 4 first elements, the sum still was a positive int, but when 5th element added, the sum changed into a negative int. I don't know why, can someone help me please?