我在最大子阵列问题中阅读了 Kadane;s 算法- 维基百科我可以理解基本的实现def max_subarray2(A): max_current = max_global = A[0] for x in A[1:]: max_current = max(x, max_current + x) if max_current> max_global: max_global = max_current return max_global声明的数据max_current = max_global = A[0]至于检索开始和结束索引的版本def max_subarray3(A): max_current = A[0] startOld = start = end = max_global = 0 for i, x in enumerate(A[1:], 1): max_current = max(x, max_current + x) max_global = max(max_global, max_current) if max_current < 0: start = i + 1 elif max_current == max_global: #when max_global not change startOld = start end = i return (max_global , startOld, end)现在max_global = 0而不是max_global = A[0],我不知道为什么。如果所有数字都是负数,则返回 (0, 0, 1)
添加回答
举报
0/150
提交
取消