
Kadane's Algorithm is a classic algorithm designed to efficiently find the maximum sum subarray within a one-dimensional array of numbers.
Instead of checking all possible subarrays—which would take time using a naive approach—Kadane's Algorithm leverages a dynamic programming insight: it
keeps track of the maximum sum ending at the current position (currentMax) and updates a global maximum (globalMax) as it scans through the array.
The key intuition is simple yet powerful: at each element, you either extend the current subarray or start a new subarray from the current element if doing so gives a larger sum. This strategy allows the algorithm to process the array in linear time , making it extremely efficient even for large inputs.
Kadane's Algorithm forms the foundation for many maximum-sum variations, including circular arrays, maximum product subarrays, and other problems where a running optimum needs to be tracked.
Before proceeding, let's remember some properties of the maximum sum subarray problem:
Kadane’s Algorithm works by scanning the array once and keeping track of two values at each step:
currentMax: the maximum subarray sum ending at the current index.globalMax: the overall maximum subarray sum found so far.A step -by-step breakdown of the algorithm is as follows:
currentMax and globalMax with the first element of the array.currentMax as the maximum between the current element and currentMax + current element. This decides whether to extend the current subarray or start a new one.globalMax if currentMax is larger.globalMax contains the maximum sum subarray.function kadane(nums: number[]): number {
let currentMax = nums[0];
let globalMax = nums[0];
for (let i = 1; i < nums.length; i++) {
currentMax = Math.max(nums[i], currentMax + nums[i]);
globalMax = Math.max(globalMax, currentMax);
}
return globalMax;
}
Current Index: 0
Current Max: 1
Global Max: 1
Current Subarray: [1]
Kadane's Algorithm is extremely efficient compared to naive approaches:
currentMax and globalMax.currentMax, globalMax, optional subarray indices).| Problem | Technique | Solution |
|---|---|---|
| Maximum Subarray | Kadane's Algorithm | Solution |
| Maximum Sum Circular Subarray | Kadane + Total Sum Trick | Solution |
| Maximum Product Subarray | Kadane-style Tracking of Max/Min | Solution |
| Best Sightseeing Pair | Kadane-style Transformation | Solution |