maximum subarray whose sum equals 0

后端 未结 12 1381
礼貌的吻别
礼貌的吻别 2020-12-04 08:14

An array contains both positive and negative elements, find the maximum subarray whose sum equals 0.

12条回答
  •  被撕碎了的回忆
    2020-12-04 08:55

    Following solution finds max length subarray with a given sum k without using dynamic programming, but using simple rescursion. Here i_s is start index and i_e is end index for the current value of sum

    ##Input the array and sum to be found(0 in your case)
    a = map(int,raw_input().split())
    k = int(raw_input())
    
    ##initialize total sum=0
    totalsum=0
    
    ##Recursive function to find max len 0
    def findMaxLen(sumL,i_s,i_e):
        if i_s0: 
            if sumL==k:
                print i_s, i_e
                return (i_s,i_e)
            else:
                x = findMaxLen(sumL-a[i_s],i_s+1,i_e)
                y = findMaxLen(sumL-a[i_e],i_s,i_e-1)
                if x[1]-x[0]>y[1]-y[0]:
                    return x
                else:
                    return y
        else:
            ##Result not there
            return (-1,-1)
    
    
    ## find total sum
    for i in range(len(a)):
        totalsum += a[i]
    
    ##if totalsum==0, max array is array itself
    if totalsum == k:
        print "seq found at",0,len(a)-1
    
    ##else use recursion
    else:
        print findMaxLen(totalsum,0,len(a)-1)
    

    Time complexity is O(n) and space complexity is O(n) due to recursive memory stack

提交回复
热议问题