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)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.