Iteration

Max Subarray Sum

Growing Window

Given an array of integers arr, return the maximum sum out of any non-empty subarray.

A subarray is a consecutive stretch of the array.

Example 1:

arr = [1,2,-1,3,-8]=> returns 5\notag \texttt{arr = [1,2,-1,3,-8]}\\[8bp] \texttt{=> returns 5}

Explanation: The largest sum you can get is 5, using the subarray [1,2,-1,3].

Example 2:

arr = [-1,-2,-3]=> returns -1\notag \texttt{arr = [-1,-2,-3]} \\[8bp] \texttt{=> returns -1}

Explanation: The largest sum you can get is -1, using the subarray [-1].

First Few Test Cases:

To solve this problem, we want to find the subarray with the largest sum. It feels like we might be able to do this in one pass. The idea to doing this is to walk left to right, adding numbers to the current sum we've seen so far, and updating the maximum sum we've seen.

This works fine, until you realize we might actually make our sum negative. If our sum goes negative, then it means we should reset the sum, and start a new window starting at the next element. This is because starting out with a negative sum will always be worse than starting a new sum from scratch.

Putting these two ideas together gives us the full solution. Here's the code:

Time Complexity O(n). We need to loop through every element in the array.

Space Complexity O(1). We store two numbers, which is O(2) = O(1).

For historical reasons this algorithm is called Kadane's Algorithm, although it' not a very interesting algorithm.

Mark as Completed:
Submits:
maxSubarraySum
Test your code to get an output here!
maxSubarraySum(
)
Test your code to get an output here!