简体   繁体   中英

Make java give the the highest sum of 3 numbers out of 4 given

When given 4 numbers, how do i find which 3 numbers out of the 4 will give the greatest sum. So if given 3 2 5 5, i want java to sum 3 5 5 for a total of 13

I have been searching for about 20 minutes and all i find is how the find the highest number of the 4 numbers. I know i absolutely can just write 16 lines of code comparing the 16 different combinations but i was hoping someone could point me in a faster direction.

First find the smallest number.

So for 3 2 5 5 it would be 2. Make sure you store this.

Thus, the numbers to sum are 3, 5 and 5

To get the total sum you need to add all the numbers together so:

3 + 2 + 5 + 5 = 15

And then minus the smallest number from the sum. So 15-2 which equals 13

First find the greatest of the four numbers and keep it aside.

Then find the greatest of the remaining three numbers and keep it aside.

Then find the greatest of the remaining two numbers and keep it aside.

Then sum up the numbers kept aside and display the result.

public static void main(String args[]) {
    int[] vals = new int[4];
    vals[0] = 3;
    vals[1] = 2;
    vals[2] = 5;
    vals[3] = 5;
    int result = sum4(vals);
    System.out.println("Sum of x+y = " + result);
}

private static int sum4(int[] nums)
{
    int retVal = 0;
    int lowest =  Integer.MAX_VALUE;
    for (int i=0; i<nums.length; i++)
    {
        if (nums[i] < lowest)
            lowest = nums[i];
        retVal += nums[i];
    }
    retVal -= lowest;
    return retVal;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM