【发布时间】:2017-02-20 20:40:05
【问题描述】:
我想知道如何降低该算法的时间复杂度。 它计算元素总和为 k 整数的最大子数组的长度。
a = 整数数组
k = 最大整数
例如:a = [1,2,3], k= 3
可能的子数组 = [1],[1,2]
最大子数组的长度 = 2
sys.setrecursionlimit(20000)
def maxLength(a, k):
#a = [1,2,3]
#k = 4
current_highest = 0
no_bigger = len(a)-1
for i in xrange(len(a)): #0 in [0,1,2]
current_sum = a[i]
sub_total = 1
for j in xrange(len(a)):
if current_sum <= k and ((i+sub_total)<=no_bigger) and (k>=(current_sum + a[i+sub_total])):
current_sum += a[i+sub_total]
sub_total += 1
else:
break
if sub_total > current_highest:
current_highest = sub_total
return current_highest
【问题讨论】:
-
问题表述不好,包含矛盾,例子不清楚。
-
最大子数组是什么意思?最大长度还是什么?
-
提示:假设数字不能为负数,请搜索部分总和以查找合作伙伴。
标签: python algorithm optimization