Maximum Subarray Sum
This problem asks for the largest sum you can get from one contiguous subarray. Contiguous means the numbers must stay next to each other in the original array, so you cannot skip a bad number in the middle and still call it one subarray.
As you scan from left to right, each position raises the same question: is it better to continue the subarray you already have, or throw it away and start fresh from the current number? That choice is the whole heart of the problem.
For example, in [-2,1,-3,4,-1,2,1,-5,4], the best subarray is [4,-1,2,1], which sums to 6. In [1], the answer is just 1. If every number is negative, like [-1,-2,-3], you still have to pick some contiguous subarray, so the answer is -1.
So the task is to find the highest possible sum of any one unbroken segment of the array and return that sum.
Example Input & Output
Since all numbers are negative, the subarray [-1] is chosen as it has the largest sum among all possible subarrays.
The array contains only one element, so the subarray [1] is the only possible subarray with a sum of 1.
The subarray [4,-1,2,1] has the largest sum = 6, as it is the contiguous sequence with the highest total when summing its elements.
Algorithm Flow

Solution Approach
The standard solution here is Kadane's algorithm. The idea is to keep track of the best subarray sum that ends at the current position, and also the best subarray sum seen anywhere so far.
Suppose we are at arr[i]. There are only two sensible choices for a subarray ending here: either start fresh at arr[i], or extend the previous subarray by adding arr[i].
That gives this update:
If the old running sum is hurting us, we drop it and start over from the current value.
At the same time, we update the overall best answer:
Putting it together:
If the array is empty, this problem's tests expect 0. Otherwise, after the loop, best is the maximum subarray sum. This runs in O(n) time and uses O(1) extra space.
Best Answers
class Solution {
public int max_subarray_sum(int[] nums) {
int maxSoFar = nums[0];
int currentMax = nums[0];
for (int i = 1; i < nums.length; i++) {
currentMax = Math.max(nums[i], currentMax + nums[i]);
maxSoFar = Math.max(maxSoFar, currentMax);
}
return maxSoFar;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
