find maximum length subarray having given sum code example

Example 1: find longest subarray by sum

def max_length(s, k):
    current = []
    max_len = -1 # returns -1 if there is no subsequence that adds up to k.
    for i in s:
        current.append(i)
        while sum(current) > k: # Shrink the array from the left, until the sum is <= k.
           current = current[1:]
        if sum(current) == k:
            max_len = max(max_len, len(current))

    return max_len

Example 2: Find maximum length sub-array having equal number of 0’s and 1’s

def findMaxLenSublist(A):
 
    # 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 zero-sum starts from index 0
    dict[0] = -1
 
    # `length` stores the maximum length of sublist with zero-sum
    length = 0
 
    # stores ending index of the maximum length sublist having zero-sum
    ending_index = -1
 
    sum = 0
 
    # Traverse through the given list
    for i in range(len(A)):
 
        # sum of elements so far (replace 0 with -1)
        sum += -1 if (A[i] == 0) else 1
 
        # if the sum is seen before
        if sum in dict:
 
            # update length and ending index of maximum length
            # sublist having zero-sum
            if length < i - dict.get(sum):
                length = i - dict.get(sum)
                ending_index = i
 
        # if the sum is seen for the first time, insert the sum with its
        # index into the dictionary
        else:
            dict[sum] = i
 
    # print the sublist if present
    if ending_index != -1:
        print((ending_index - length + 1, ending_index))
    else:
        print("No sublist exists")

Example 3: max subsequence sum in array

def max_subarray(numbers):
    """Find the largest sum of any contiguous subarray."""
    best_sum = 0  # or: float('-inf')
    current_sum = 0
    for x in numbers:
        current_sum = max(0, current_sum + x)
        best_sum = max(best_sum, current_sum)
    return best_sum

Tags:

Misc Example