问题:给出一个整数数组,要找出元素之和最大的子数组。
如有列表A
A = [-2, -4, 3, -1, 5, 6, -7, -2, 4, -3, 2]
算法1:
def maxsub_1(A):
m = 0
for j in range(len(A)):
for k in range(j, len(A)):
s = 0
for i in range(j, k+1):
s += A[i]
if s > m:
m = s
return m
分析:外层循环变量j迭代n次,内层循环变量k最多迭代n次,最内层循环变量i最多迭代n次,因此算法复杂度为O(n3)
算法2:
考虑Si为前i个元素之和(前缀和),则Aj加到Ak可表示为Sk - Sj-1,则有以下算法
def maxsub_2(A):
S = [0]
S = S * len(A)
S[0] = A[0]
for i in range(1, len(A)):
S[i] = S[i-1] + A[i]
S.append(S[i])
m = 0
for j in range(len(A)):
for k in range(j, len(A)):
s = S[k] - S[j-1]
if s > m:
m = s
return m
分析:i层循环变量迭代n-1次,复杂度O(n),外层循环变量j迭代n次,内层循环变量k最多迭代n次,内层循环体(减法计算)复杂度只需要O(1),复杂度为O(n2),因此总复杂度为O(n)+O(n2)=O(n2)
算法3:
放弃前缀和,考虑后缀和M,则有以下算法
def maxsub_3(A):
M = [0]
M = M * len(A)
M[0] = 0
for t in range(len(A)):
M[t] = max(0, M[t-1]+A[t])
m = 0
for t in range(len(A)):
m = max(m, M[t])
return m
分析:复杂度为O(n)