DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

SalahElhossiny
SalahElhossiny

Posted on

Maximum Subarray

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

A subarray is a contiguous part of an array.

class Solution(object):
    def maxSubArray(self, nums):        
        sumS = nums[0]
        sumL = 0

        l = len(nums)

        if l == 1:
            return sumS


        for i in range(l):
            sumL += nums[i]

            sumS = max(sumS, sumL)

            if sumL < 0:
                sumL = 0


        return sumS

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
isabelagomes profile image
IsabelaGomes

How do you approach a maximum subarray sum? rituel magie blanche amour

πŸ€” Did you know?

Β 
🌚 You can turn on dark mode in Settings