我需要一些C#帮助。我有一个带有5个值的整数数组:
Int[] arrayValues = { 10, 8, 6, 5, 3 };
我需要找到三个值(10种组合可能性)的任意组合的最大值,然后重新排列这些值,使得具有最大总和的3个值位于最后3个位置。
答案 0 :(得分:1)
算法是:
代码是这样的(它可以被优化),
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
答案 1 :(得分:0)
它只是按升序排序的数组。
arrayValues.sort()
应该工作并按升序列出数字