了解 Kadane 算法 (Python) 中发生的事情

Wil*_*ski 6 python algorithm python-3.x kadanes-algorithm

我很难理解在我发现的 Kadane 算法的这两个例子中发生了什么。我是 Python 新手,我希望理解这个复杂的算法将帮助我更好地查看/阅读程序。

为什么一个例子比另一个更好,它只是List vs Range吗?还有其他什么可以使示例之一更有效吗?此外,还有一些关于计算中发生了什么的问题。(例子中的问题)

我已经使用PythonTutor帮助我逐步了解到底发生了什么。

示例 1:

在 PythonTuter 中,当您在提供的屏幕截图中选择下一步时,so_far 的值变为 1。这是怎么回事?给出总和,我认为它加上 -2 + 1 即 -1,所以当 so_far 变成 1 时,这是怎么回事?

        def max_sub(nums):
            max_sum = 0
            so_far = nums[0]
        
            for x in nums[1:]:
                so_far = max(x, x + so_far)
                max_sum = max(so_far, max_sum)
            return max_sum
        
nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
    max_sub(nums)
                6 
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

示例 2:

与此类似的问题,当我选择 NEXT 步骤时,max_sum 从 -2 变为 4 ......但是如果将元素添加到 2(即 4)中会怎样。对我来说,那将是 -2 + 4 = 2 ?

def maxSubArraySum(a,size):
     
    max_so_far =a[0]
    curr_max = a[0]
     
    for i in range(1,size):
        curr_max = max(a[i], curr_max + a[i])
        max_so_far = max(max_so_far,curr_max)
         
    return max_so_far
 
a = [-2, -3, 4, -1, -2, 1, 5, -3]
print("Maximum contiguous sum is" , maxSubArraySum(a,len(a)))
     Maximum contiguous sum is 7
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

所以,这将是一个两部分的问题,而不是:

[1]Based on understandings, why would one be more pythonic and more efficient than the other? 
[2]How can I better understand the calculations happening in the examples?
Run Code Online (Sandbox Code Playgroud)

Dan*_*Hao 1

只要观察每一步,你就可以弄清楚这个问题: [注释]这个程序似乎是基于混合整数的假设来工作的?只有积极和消极。

# starting
so_far  = -2   # init. to nums[0]
max_sum = 0

# in the for-loop:
x =  1         # starting with nums[1:]
so_far = max(1, -1)   -> 1   (x is 1, -2 + 1)
max_sum = max(0, 1)   -> 1
.....   continue .... each step is to find the max accumulated numbers sum, as it's evident in the max( ) statement.  *There is no `sum` involved, except it tried to determine the current x is good (not negative) then so add it to the so_far.
Run Code Online (Sandbox Code Playgroud)