我需要一些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