largest subarray sum Algorithm

This problem can be solved use several different algorithmic techniques, including brute force, divide and conquer, dynamic programming, and reduction to shortest paths. If the array contains all non-positive numbers, then a solution is any subarray of size 1 containing the maximal value of the array (or the empty subarray, if it is allowed). The maximal subarray problem was proposed by Ulf Grenander in 1977 as a simplified model for maximal likelihood estimate of shapes in digitized pictures. 

There is some evidence that no significantly faster algorithm exists; an algorithm that solves the two-dimensional maximal subarray problem in O(n3−ε) time, for any ε>0, would imply a similarly fast algorithm for the all-pairs shortest paths problem. Grenander derived an algorithm that solves the one-dimensional problem in O(n2) time, better the brute force working time of O(n3).
from sys import maxsize


def max_sub_array_sum(a: list, size: int = 0):
    """
    >>> max_sub_array_sum([-13, -3, -25, -20, -3, -16, -23, -12, -5, -22, -15, -4, -7])
    -3
    """
    size = size or len(a)
    max_so_far = -maxsize - 1
    max_ending_here = 0
    for i in range(0, size):
        max_ending_here = max_ending_here + a[i]
        if max_so_far < max_ending_here:
            max_so_far = max_ending_here
        if max_ending_here < 0:
            max_ending_here = 0
    return max_so_far


if __name__ == "__main__":
    a = [-13, -3, -25, -20, 1, -16, -23, -12, -5, -22, -15, -4, -7]
    print(("Maximum contiguous sum is", max_sub_array_sum(a, len(a))))

LANGUAGE:

DARK MODE: