DEV Community

Bernice Waweru
Bernice Waweru

Posted on • Edited on

2 1

Maximum Subarray Sum

Instructions

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.

Example

Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.

Approach

We can initialize maximum sum at index 0 and update it as we iterate through the array when we find a new maximum.
We also initialize a current sum at index 0 and update it by adding num at current index. We also compare if current sum is greater than num at current index and update it. We then compare if the current sum is greater than maximum sum and update maximum sum.

Python Implementation

def maxSubArray(nums):
    if not nums:
        return 0
    currSum = maxSum = nums[0]
    for i in range(1,len(nums)):
        currSum += nums[i]
        currSum = max(currSum, nums[i])
        maxSum  = max(maxSum, currSum)
    return maxSum
Enter fullscreen mode Exit fullscreen mode

The space complexity is O(1) because we do not use an extra memory and the time complexity is O(n) because we have to go through each element in the array.

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay