简体   繁体   English

使java给出4个给定数字中3个数字的最大和

[英]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.当给定 4 个数字时,我如何找到 4 个数字中的哪 3 个数字的总和最大。 So if given 3 2 5 5, i want java to sum 3 5 5 for a total of 13因此,如果给定 3 2 5 5,我希望 java 将 3 5 5 相加,总共 13

I have been searching for about 20 minutes and all i find is how the find the highest number of the 4 numbers.我已经搜索了大约 20 分钟,我发现的只是如何找到 4 个数字中的最高数字。 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.我知道我绝对可以写 16 行代码来比较 16 种不同的组合,但我希望有人能指出我更快的方向。

First find the smallest number.先找出最小的数。

So for 3 2 5 5 it would be 2. Make sure you store this.因此,对于 3 2 5 5,它将是 2。确保您存储它。

Thus, the numbers to sum are 3, 5 and 5因此,要求和的数字是 3、5 和 5

To get the total sum you need to add all the numbers together so:要获得总和,您需要将所有数字加在一起,以便:

3 + 2 + 5 + 5 = 15 3 + 2 + 5 + 5 = 15

And then minus the smallest number from the sum.然后从总和中减去最小的数字。 So 15-2 which equals 13所以 15-2 等于 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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