我有以下Kadane 算法的实现来解决数组的最大子数组的问题:
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]
.
对于我的一生,我找不到错误在哪里。也许是算法设计的缺陷?
提前致谢。