Tuesday, February 22, 2022

Maximum subarray sum Python Codewars

Task:

The maximum sum subarray problem consists in finding the maximum sum of a contiguous subsequence in an array or list of integers:

max_sequence([-2, 1, -3, 4, -1, 2, 1, -5, 4])
# should be 6: [4, -1, 2, 1]

Easy case is when the list is made up of only positive numbers and the maximum sum is the sum of the whole array. If the list is made up of only negative numbers, return 0 instead.

Empty list is considered to have zero greatest sum. Note that the empty list or array is also a valid sublist/subarray.

Solution:


def max_sequence(arr):
    max = 0
    sub_max = 0
    for i in arr:
        if sub_max > 0:
            sub_max += i
            if sub_max < 0:
                sub_max = 0
            elif sub_max > max:
                max = sub_max
        elif i > 0:
            sub_max += i

    return max

def maxSequence(arr):
    max,curr=0,0
    for x in arr:
        curr+=x
        if curr<0:curr=0
        if curr>max:max=curr
    return max


print(max_sequence([-2, 1, -3, 4, -1, 2, 3, -2, -5, 4]))


Training on Maximum subarray sum | Solution | Codewars



Related Posts


No comments :

Post a Comment