find subarray with maximum length python code example

Example: Find maximum length sublist with sum `S` present in a given list

def findMaxLenSublist(A, S):
 
    # create an empty dictionary to store the ending index of the first
    # sublist having some sum
    dict = {}
 
    # insert `(0, -1)` pair into the set to handle the case when a
    # sublist with sum `S` starts from index 0
    dict[0] = -1
 
    sum = 0
 
    # `length` stores the maximum length of sublist with sum `S`
    length = 0
 
    # stores ending index of the maximum length sublist having sum `S`
    ending_index = -1
 
    # traverse the given list
    for i in range(len(A)):
 
        # sum of elements so far
        sum += A[i]
 
        # if the sum is seen for the first time, insert the sum with its
        # into the dictionary
        if sum not in dict:
            dict[sum] = i
 
        # update length and ending index of the maximum length sublist
        # having sum `S`
        if sum - S in dict and length < i - dict[sum - S]:
            length = i - dict[sum - S]
            ending_index = i
 
    # print the sublist
    print((ending_index - length + 1, ending_index))