查找Java中的最大组合总数

use*_*575 5 java algorithm set mathematical-optimization

假设您有一组如下数字:

[A,B,C]

[6, 4.5, 6]
[7, 6, 5]
[9, 4.5, 6]
Run Code Online (Sandbox Code Playgroud)

每个集合中只有一个数字类别(A,B或C)可用于查找最大总和.在这种情况下,A = 9,B = 6和C = 6将产生21的最大总和.最大的总和不能是22(9 + 7 + 6),因为9和7都是A类冲突.

我怎么能用Java做到这一点?

我无法找到最大的金额,因为在每个类别中选择最大值并不能保证最大的金额.某些类别可能会被强制为较小的值,从而减少总和.请记住,每个集合和类别中只能选择一个数字.

Bal*_*des -2

以下是关于我将如何做到这一点的一些想法。

假设您将数据存储在二维整数数组中

int [] [] data = new int [rows] [columns]
Run Code Online (Sandbox Code Playgroud)

所以在本例中,列是 A、B、C 等。

搜索最大值时需要这样迭代:

data[i][fix]所以列是固定的,行是在循环中改变的

在您的示例中,如果您想获得最大值A并且像我建议的那样使用二维数组,那么:

int [] [] data = new int [3][3];
Run Code Online (Sandbox Code Playgroud)

那么您需要从 中获取最大值的集合Adata [0][0]data[1][0]并且data[2][0]

编辑:

这是为您提供的一种可能的解决方案。

//here is our data array.
int [][] data = new int[3][];

//fill up with som random data
data[0] = new int[]{10,20,4,5,56,87,9};
data[1] = new int[]{1,65,0,10,3};
data[2] = new int[]{34,5,6,67,3,54};

//get the biggest arrays length
int maxArrayLength = 0;
for(int i=1; i<data.length; i++)
{
    if(data[i].length > data[maxArrayLength].length)
        maxArrayLength = i;
}
maxArrayLength = data[maxArrayLength].length;

//collect the max in each category
int [] categoryMax = new int[maxArrayLength];

//loop through the categories
for(int i=0; i<maxArrayLength; i++)
{
    //in each iteration we get a winner
    int categoryWinner = 0;

    // now loop through the values of the current category
    for(int j=0; j<data.length; j++)
    {
        int [] actualArray = data[j];
        int [] winnerArray = data[categoryWinner];

        //check if we are in the bounds, if so, then perform a simple maxsearch
        if(i<actualArray.length)
            if(actualArray[i] > winnerArray[i])
            categoryWinner = j;
    }

    //set the current element of the winners array.
    categoryMax [i] = data[categoryWinner][i];
}

int sum = 0;

// we are ready, print it out!
for(int i=0; i<categoryMax.length; i++)
{
    System.out.println((i+1) + ". groups winner: " + categoryMax[i]);
    sum+=categoryMax[i];
}
System.out.println(sum);
Run Code Online (Sandbox Code Playgroud)