无法实现此python程序以查找具有2D数组最大和的子数组的和
想要:返回2D数组的最大和子数组的和 在下面的程序中,我首先计算边界列为L和R的最大和子数组的和,其中L从0运行到(cols-1),R从L运行到(cols-1),cols是列数,行数是行数。很明显,要求的答案是所有这些值中的最大值。我也在更新最大和,max,以及 我的函数max_sum_of_subarray_in_1D_array(A,n)返回O(n)时间内1D array的最大子数组之和,此函数工作正常无法实现此python程序以查找具有2D数组最大和的子数组的和,python,arrays,algorithm,max,Python,Arrays,Algorithm,Max,想要:返回2D数组的最大和子数组的和 在下面的程序中,我首先计算边界列为L和R的最大和子数组的和,其中L从0运行到(cols-1),R从L运行到(cols-1),cols是列数,行数是行数。很明显,要求的答案是所有这些值中的最大值。我也在更新最大和,max,以及 我的函数max_sum_of_subarray_in_1D_array(A,n)返回O(n)时间内1D array的最大子数组之和,此函数工作正常 def max_sum_of_subarray_in_1D_array(A, 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\u sum\u工作不正常
内部:
循环您需要重新分配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))
def\u 1D\u阵列中的子阵列的最大和(a,大小):
到目前为止的最大值=-1000000
此处的最大值=0
对于范围内的i(0,大小):
max_ending_here=max_ending_here+a[i]
如果(到目前为止的最大值<此处的最大值):
max\u so\u far=max\u ending\u此处
如果此处的最大值小于0:
此处的最大值=0
返回到目前为止的最大值
def 2D_数组中_子数组的最大_和(A、行、列):
温度=[]
maxValue=-1000000
对于范围内的L(0,cols):
温度=[]
对于范围(0,行)中的i:
临时附加(0)
对于范围内的R(L,cols):
对于范围(0,行)中的i:
温度[i]+=A[i][R]
val=一维数组中的子数组的最大和(临时,行)
如果val>maxValue:
最大值=val
返回最大值
A=[[1,2,-1,-4,-20],
[-8, -3, 4, 2, 1],
[3, 8, 10, 1, 3],
[-4, -1, 1, 7, -6]]
打印(二维数组(A,4,5)中子数组的最大和)
希望这有帮助 多谢各位。但我仍然无法理解为什么我的1D数组算法不起作用:(@AshwiniPatil通常为了理解我程序中的错误,我用纸和笔一步一步地去看看可能是什么问题。