Learn
Kadane's Algorithm
Kadane's Algorithm finds the maximum sum of any contiguous subarray in time with a single pass. It's a classic example of dynamic programming with space.
At each position, you decide whether to extend the previous subarray or start a new one. You extend if the previous sum is positive.
function maxSubarraySum(arr, n):
maxSum = arr[0]
currentSum = arr[0]
for i from 1 to n - 1:
currentSum = max(arr[i], currentSum + arr[i])
maxSum = max(maxSum, currentSum)
return maxSum
If your becomes negative, starting fresh at the current element is always better than carrying the negative sum forward.