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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay