2010-12-12 124 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