Refer the problem statement: Maximum Subarray Sum
Let us try to understand how Kadane’s Algorithm work. This solution is similar to sliding window in a way.
Pseudocode
For at-least 1 non-negative numbers
Here’s the pseudocode for Kadane’s algorithm based on your template, designed to handle arrays with non-negative sums:
|
|
maxGlobal
is sometimes denoted as maxSoFar
and maxCurrent
is denoted as maxEndingHere
.
Please note that the above pseudocode initializes maxGlobal
and maxCurrent
to 0, which assumes there will be at least one non-negative number in the input array.
We can rewrite it as (removing if
condition and using max()
function instead):
|
|
For all negative number
If the array can be entirely negative, the initialization should be changed to handle this by setting maxGlobal
and maxCurrent
to the first element of the array or to negative infinity to correctly find the maximum subarray sum, which might still be negative.
Here’s the adjusted pseudocode for arrays that could contain all negative numbers:
|
|
So we made 2 changes:
- Initial maxGlobal and
maxCurrent
witha[0]
- Instead of updating
maxCurrent
to 0, we update witharr[i]
in case of max.
Code
Original
Java
|
|
Modified Kadane
Java
|
|
Limitation of the Algorithm
So, remember to use modified Kadane’s algorithm, when the array contains only negative numbers. Original Kadane’s algorithm will return the value of the largest negative element rather than a sum, because the algorithm is designed to look for positive contiguous sequences. This may or may not be desired, depending on whether empty subarrays with a sum of 0 are considered valid.