-4

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?

khelwood
  • 55,782
  • 14
  • 81
  • 108

2 Answers2

0

I guess you should use long as summin and summax, that would solve your problem (you have negative values because you sum max is more than max integer value)

Ilya Mezhov
  • 111
  • 4
0

You are exceeding the range of integer and the value is overflowing to the negative side. If you want to test with big numbers use long datatype.

Int Datatype Rang:

-2,147,483,648 to 2,147,483,647 The int data type is a 32-bit signed Java primitive data type. A variable of the int data type takes 32 bits of memory. Its valid range is -2,147,483,648 to 2,147,483,647 (-231 to 231– 1).