【发布时间】:2015-05-01 04:54:21
【问题描述】:
在 Python 中,找到数组范围内元素的最大总和的最佳方法是什么?
例如一个数组[1,-3,2,5,-5]
在数组中的任何其他范围中,元素总和为最大正数的范围是多少?结果必须是数组的开始和结束位置的索引。
【问题讨论】:
-
最佳解决方案就在上面在上面的维基百科文章中——在 Python 中。我怀疑你能比
O(n)
标签: python arrays sum logic range
在 Python 中,找到数组范围内元素的最大总和的最佳方法是什么?
例如一个数组[1,-3,2,5,-5]
在数组中的任何其他范围中,元素总和为最大正数的范围是多少?结果必须是数组的开始和结束位置的索引。
【问题讨论】:
O(n)
标签: python arrays sum logic range
我首先通过 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
【讨论】: