在Python中,什么是查找数组范围内元素的最大总和的最佳方法?
e.g。一个数组[1,-3,2,5,-5]
元素之和的范围是数组中任何其他范围最正的范围是多少?结果必须是数组的起始和结束位置的索引。
答案 0 :(得分:2)
我首先通过Jon Bentley的书了解到这个问题。为了处理带有负数的列表,我添加了自己的修改:
def largest(sequence):
"""
This is based on Bentley's Programming Pearls chapter 8.
My modification: if the sequence is all negatives
then max is the largest element
"""
max_so_far = max_up_to_here = 0
largest_element = sequence[0]
all_negatives = True
for element in sequence:
max_up_to_here= max(max_up_to_here + element, 0)
max_so_far = max(max_so_far, max_up_to_here)
largest_element = max(largest_element, element)
if element >= 0:
all_negatives = False
if all_negatives:
return largest_element
return max_so_far