find maximum subarray having maximum sum code example
Example 1: 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 2: 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