The Maximum Subarray

  • + 0 comments
    def maxSubarray(arr):
        max_ar, max_se = arr[0], 0
        curr_ar = 0
        for val in arr:
            # calculate maximum subarray
            curr_ar = max(val, curr_ar + val)
            max_ar = max(max_ar, curr_ar)
            # calculate maximum subsequence
            if val > 0:
                max_se += val
        # if all val in arr are negative
        if max_se == 0:
            max_se = max(arr)
        
        return max_ar, max_se