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
Finding the sub array that has maximum sum JavaScript
We are required to write a JavaScript function that takes in an array of numbers. The array can contain both positive and negative numbers.
The purpose of our function is to find the subarray (of any length) whose elements when summed give the maximum sum. This problem is known as the Maximum Subarray Problem and is commonly solved using Kadane's Algorithm.
For example, if the input array is:
const arr = [-2,1,-3,4,-1,2,1,-5,4];
Then the output should be:
6
Because the subarray [4,-1,2,1] has the largest sum of 6.
How Kadane's Algorithm Works
Kadane's algorithm uses dynamic programming to solve this problem efficiently in O(n) time complexity. The key insight is to keep track of the maximum sum ending at each position.
Example
const arr = [-2,1,-3,4,-1,2,1,-5,4];
const maxSubArray = (arr = []) => {
let sum = arr[0], max = arr[0];
for (let i = 1; i
Output
6
Step-by-Step Explanation
The algorithm works by maintaining two variables:
- sum: Maximum sum of subarray ending at current position
- max: Maximum sum found so far
At each element, we decide whether to extend the existing subarray or start a new one by comparing sum + arr[i] with arr[i].
Alternative Implementation with Subarray Tracking
const arr = [-2,1,-3,4,-1,2,1,-5,4];
const maxSubArrayWithIndex = (arr = []) => {
let maxSum = arr[0];
let currentSum = arr[0];
let start = 0, end = 0, tempStart = 0;
for (let i = 1; i maxSum) {
maxSum = currentSum;
start = tempStart;
end = i;
}
}
console.log(`Maximum sum: ${maxSum}`);
console.log(`Subarray: [${arr.slice(start, end + 1).join(', ')}]`);
console.log(`Indices: ${start} to ${end}`);
return maxSum;
};
maxSubArrayWithIndex(arr);
Output
Maximum sum: 6 Subarray: [4, -1, 2, 1] Indices: 3 to 6
Conclusion
Kadane's Algorithm efficiently solves the maximum subarray problem in O(n) time complexity. It's a classic example of dynamic programming where we make optimal decisions at each step to find the global maximum.
