我有以下实现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]
。
我真的找不到错误在哪里。也许这是算法设计上的缺陷?
提前感谢。