[英]Unable to implement this python program to find the sum of the subarray with maximum sum of a 2D array
想要:返回二维数组的最大和子数组的总和
在下面的程序中,我首先计算最大和子数组的总和,其边界列是 L 和 R,其中 L 从 0 到 (cols-1) 运行,R 从 L 运行到 (cols-1),cols 是列和行是行数。 然后很明显,所需的答案是所有这些值中的最大值。 我也在更新最大总和 max。
我的函数 max_sum_of_subarray_in_1D_array(A, n) 在 O(N) 时间内返回一维数组的最大子数组的总和,该函数运行良好。
def max_sum_of_subarray_in_1D_array(A, n):
for i in range(1, n):
A[i] = max(A[i], A[i]+A[i-1])
iMax = 0
for i in range(1, n):
if A[i] > A[iMax]:
iMax = i
return A[iMax]
def max_sum_of_subarray_in_2D_array(A, rows, cols):
temp = []
max = -1000000
for L in range(0, cols):
for i in range(0, rows):
temp.append(0)
for R in range(L, cols):
for i in range(0, rows):
temp[i] += A[i][R]
val = max_sum_of_subarray_in_1D_array(temp, rows);
if val > max:
max = val
return max
A = [[1, 2, -1, -4, -20],
[-8, -3, 4, 2, 1],
[3, 8, 10, 1, 3],
[-4, -1, 1, 7, -6]]
print(max_sum_of_subarray_in_2D_array(A, 4, 5))
但是我得到 1024 的错误输出
正确输出:29
有人可以指出我做错的地方。 我看了一遍又一遍,找不到错误。
基本上你的代码中有两个问题:-
max_sum_of_subarray_in_1D_array()
工作不正常。for L in range(0, cols):
循环内部,您需要重新分配temp = []
,否则您将继续附加值并且总和将增加,这会给您错误的输出。我正在发布更新的代码,请参考。
def max_sum_of_subarray_in_1D_array(a, size):
max_so_far = -1000000
max_ending_here = 0
for i in range(0, size):
max_ending_here = max_ending_here + a[i]
if (max_so_far < max_ending_here):
max_so_far = max_ending_here
if max_ending_here < 0:
max_ending_here = 0
return max_so_far
def max_sum_of_subarray_in_2D_array(A, rows, cols):
temp = []
maxValue = -1000000
for L in range(0, cols):
temp = []
for i in range(0, rows):
temp.append(0)
for R in range(L, cols):
for i in range(0, rows):
temp[i] += A[i][R]
val = max_sum_of_subarray_in_1D_array(temp, rows)
if val > maxValue:
maxValue = val
return maxValue
A = [[1, 2, -1, -4, -20],
[-8, -3, 4, 2, 1],
[3, 8, 10, 1, 3],
[-4, -1, 1, 7, -6]]
print(max_sum_of_subarray_in_2D_array(A, 4, 5))
希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.