我很难理解我发现的 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
示例 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
所以,这将是一个两部分的问题,而不是:
[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?