2010-12-12 123 views
-1

我需要一些C#帮助。我有整数的5个值的数组:查找数组子集的最大值


Int[] arrayValues = { 10, 8, 6, 5, 3 }; 

我需要找到三个值(10组合可能性),然后任意组合的最大值重新排列的值,以使3个值具有最大总和处于最后3个位置。

+6

你需要做的不仅仅是发表您的要求的问题。告诉我们你尝试过的一些事情;给我们一些证据表明你已经考虑过这个问题以及如何最好地解决这个问题。最好向我们展示一个无法正常工作的代码示例。但最重要的是,*询问实际问题*。 – 2010-12-12 15:45:16

+0

作业?(15个字符...) – 2010-12-12 15:46:22

+1

找到了,10个是最大的:) – 2010-12-12 15:52:05

回答

1

的算法是:

  1. 按升序的顺序排列
  2. 最后3个元素是美国的3个大要素阵列即最大合计的组合
  3. 查找最大元素的总和
  4. 将非最大元素存储在结果数组中,从而保持原始顺序。
  5. 追加结果数组末尾的最大元素。

的代码是这样的(它可以被优化),

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 
0

这只是按升序排列的数组。

arrayValues.sort() 

应该工作,并在升序列表中的号码

+1

我想你的意思是'Array.Sort(arrayValues);' – 2010-12-12 15:55:08

+0

@Cody:是的对不起,我大部分时间使用IEnumerable,我倾向于Array.sort()和IEnumerable.sort()混合起来 – gprasant 2010-12-12 15:58:48

+1

既没有一个'Array.sort'和一个'IEnumerable.sort'。有一个'Array.Sort',但没有'IEnumerable.Sort'。 – jason 2010-12-13 05:28:20