我需要一些C#帮助。我有整数的5个值的数组:查找数组子集的最大值
Int[] arrayValues = { 10, 8, 6, 5, 3 };
我需要找到三个值(10组合可能性),然后任意组合的最大值重新排列的值,以使3个值具有最大总和处于最后3个位置。
我需要一些C#帮助。我有整数的5个值的数组:查找数组子集的最大值
Int[] arrayValues = { 10, 8, 6, 5, 3 };
我需要找到三个值(10组合可能性),然后任意组合的最大值重新排列的值,以使3个值具有最大总和处于最后3个位置。
的算法是:
的代码是这样的(它可以被优化),
int[] orginalArray = { 10, 8, 6, 5, 3 };
int[] copyArray = new int[orginalArray.Length];
int[] resultArray = new int[orginalArray.Length];
// Make a copy of the orginal array
Array.Copy(orginalArray,0, copyArray, 0,orginalArray.Length);
// Sort the copied array in ascendng order (last 3 elements are the largest 3 elements)
Array.Sort(copyArray);
// Array to store the largest elements
int[] largest = new int[3];
for (int i = copyArray.Length - 3, j = 0; i < copyArray.Length; i++, j++)
{
largest[j] = copyArray[i];
}
// Sum of the largest elements
int largestSum = largest.Sum();
// Copy the non largest elements to the result array (in the original order)
for (int i = 0, j=0; i < orginalArray.Length; i++)
{
if (!largest.Contains(orginalArray[i]))
{
resultArray[j++] = orginalArray[i];
}
}
// Copy the largest elements to the last 3 positions
for(int i=largest.Length - 1, j=0;i<resultArray.Length;i++, j++)
{
resultArray[i] = largest[j];
}
// Result - resultArray[] : 5 3 6 8 10
// Largest sum combination - largest[]: 6 8 10
// Sum of largest combination - largestSum: 24
这只是按升序排列的数组。
arrayValues.sort()
应该工作,并在升序列表中的号码
你需要做的不仅仅是发表您的要求的问题。告诉我们你尝试过的一些事情;给我们一些证据表明你已经考虑过这个问题以及如何最好地解决这个问题。最好向我们展示一个无法正常工作的代码示例。但最重要的是,*询问实际问题*。 – 2010-12-12 15:45:16
作业?(15个字符...) – 2010-12-12 15:46:22
找到了,10个是最大的:) – 2010-12-12 15:52:05