【问题标题】:Best way to find the most maximum sum of a range in array找到数组中范围的最大和的最佳方法
【发布时间】:2015-05-01 04:54:21
【问题描述】:

在 Python 中,找到数组范围内元素的最大总和的最佳方法是什么?

例如一个数组[1,-3,2,5,-5]

在数组中的任何其他范围中,元素总和为最大正数的范围是多少?结果必须是数组的开始和结束位置的索引。

【问题讨论】:

标签: python arrays sum logic range


【解决方案1】:

我首先通过 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    

【讨论】:

  • 谢谢。你救了我。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-06
  • 1970-01-01
相关资源
最近更新 更多