【问题标题】:Reducing time complexity of contiguous subarray降低连续子数组的时间复杂度
【发布时间】: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


【解决方案1】:

您可以为此使用sliding window 算法。

index 0 开始,在前进的过程中计算子数组的总和。当 sum 超过 k 时,开始递减初始元素,直到 sum 再次小于 k 并再次开始求和。

找到下面的python代码:

def max_length(a,k):
    s = 0
    m_len = 0
    i,j=0,0
    l = len(a)
    while i<l:
        if s<=k and m_len<(j-i):
            m_len = j-i
        print i,j,s
        if s<=k and j<l:
            s+=a[j]
            j+=1
        else:
            s-=a[i]
            i+=1
    return m_len

a = [1,2,3]
k = 3
print max_length(a,k)

输出:

2

【讨论】:

    猜你喜欢
    • 2011-06-15
    • 2014-03-30
    • 2012-07-28
    • 2016-10-07
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多