【发布时间】:2012-03-27 13:12:38
【问题描述】:
我有以下Kadane's algorithm的实现来解决数组最大子数组的问题:
public static decimal FindBestSubsequence
(this IEnumerable<decimal> source, out int startIndex, out int endIndex)
{
decimal result = decimal.MinValue;
decimal sum = 0;
int tempStart = 0;
List<decimal> tempList = new List<decimal>(source);
startIndex = 0;
endIndex = 0;
for (int index = 0; index < tempList.Count; index++)
{
sum += tempList[index];
if ((sum > result) ||
(sum == result && (endIndex - startIndex) < (index - tempStart)))
{
result = sum;
startIndex = tempStart;
endIndex = index;
}
else if (sum < 0)
{
sum = 0;
tempStart = index + 1;
}
}
return result;
}
当我使用以-1, 2, 3 之类的负数开头的序列时,它会失败,结果是4, [0,2] 而不是5, [1,2]。
为了我的一生,我找不到错误在哪里。可能是算法设计的缺陷?
提前致谢。
【问题讨论】:
标签: c# .net algorithm kadanes-algorithm