Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Using Kadane’s algorithm to find maximum sum of subarray in JavaScript
Kadane's algorithm is a powerful dynamic programming technique used to find the maximum sum of a contiguous subarray within an array. This algorithm is particularly useful for solving problems involving sequences of numbers where you need to find the optimal contiguous subsequence.
Problem Statement
Given an array of integers, find the contiguous subarray with the maximum sum and return that sum.
Sample Input:
arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]
Sample Output:
Maximum sum: 6 (from subarray [4, -1, 2, 1])
Method 1: Naive Approach
The brute force approach examines every possible subarray to find the one with maximum sum. It uses nested loops to generate all subarrays and tracks the maximum sum found.
function maxSubarraySum(arr) {
let maxSum = -Infinity;
for (let i = 0; i < arr.length; i++) {
let sum = 0;
for (let j = i; j < arr.length; j++) {
sum += arr[j];
maxSum = Math.max(maxSum, sum);
}
}
return maxSum;
}
const arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
console.log(`Maximum Sum: ${maxSubarraySum(arr)}`);
Maximum Sum: 6
Time Complexity: O(n²) - inefficient for large arrays
Method 2: Kadane's Algorithm
Kadane's algorithm solves this problem in linear time using dynamic programming. It maintains two variables: the maximum sum ending at the current position and the overall maximum sum found so far.
function kadaneAlgorithm(arr) {
let maxEndingHere = arr[0];
let maxSoFar = arr[0];
for (let i = 1; i < arr.length; i++) {
// Either extend existing subarray or start new one
maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);
// Update overall maximum
maxSoFar = Math.max(maxSoFar, maxEndingHere);
}
return maxSoFar;
}
const arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
console.log(`Maximum Sum: ${kadaneAlgorithm(arr)}`);
Maximum Sum: 6
Time Complexity: O(n) - optimal solution
Method 3: Kadane's Algorithm with Subarray Indices
This enhanced version not only finds the maximum sum but also tracks the start and end indices of the subarray that produces this sum.
function kadaneWithIndices(arr) {
let maxEndingHere = arr[0];
let maxSoFar = arr[0];
let start = 0, end = 0, tempStart = 0;
for (let i = 1; i < arr.length; i++) {
if (arr[i] > maxEndingHere + arr[i]) {
maxEndingHere = arr[i];
tempStart = i;
} else {
maxEndingHere += arr[i];
}
if (maxEndingHere > maxSoFar) {
maxSoFar = maxEndingHere;
start = tempStart;
end = i;
}
}
return {
maxSum: maxSoFar,
subarray: arr.slice(start, end + 1),
startIndex: start,
endIndex: end
};
}
const arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
const result = kadaneWithIndices(arr);
console.log(`Maximum Sum: ${result.maxSum}`);
console.log(`Subarray: [${result.subarray.join(', ')}]`);
console.log(`Indices: ${result.startIndex} to ${result.endIndex}`);
Maximum Sum: 6 Subarray: [4, -1, 2, 1] Indices: 3 to 6
How Kadane's Algorithm Works
Comparison of Methods
| Method | Time Complexity | Space Complexity | Returns Subarray |
|---|---|---|---|
| Naive Approach | O(n²) | O(1) | No |
| Kadane's Algorithm | O(n) | O(1) | No |
| Kadane's with Indices | O(n) | O(1) | Yes |
Key Points
- Kadane's algorithm works by deciding at each step whether to extend the current subarray or start a new one
- It maintains the maximum sum ending at current position and the overall maximum found so far
- The algorithm handles all-negative arrays correctly by returning the least negative number
- Time complexity is O(n) making it optimal for large datasets
Conclusion
Kadane's algorithm provides an elegant O(n) solution to the maximum subarray problem. Its dynamic programming approach efficiently tracks optimal subarrays by making local decisions that lead to the global optimum, making it essential for competitive programming and real-world applications.
