Table of contents
This is a cool problem. We need to find the contiguous subarray with the largest sum in an array. We will start by writing a brute force approach and then we will solve it using Kadane's Algorithm.
Brute Force
We will simply go through all the contiguous subarrays present in the array and compare each of their sums to find out the maximum. Here is an implementation of this approach:
function max_sum_subarr(arr) {
let gmax = Number.MIN_SAFE_INTEGER;
let cmax = 0;
for (let i = 0; i < arr.length; i++) {
for (let j = i; j < arr.length; j++) {
cmax += arr[j];
gmax = Math.max(gmax, cmax);
}
cmax = 0;
}
return gmax;
}
console.log(max_sum_subarr([1, 2, 3, -2, 5]));
-> 9
As you can see we need require a nested loop for this approach. The time complexity of this code is O(n^2)
. We can bring it down to O(n)
with Kadane's Algorithm.
Note: I would recommend you to dry run the above code before moving to the next approach.
Kadane's Algorithm
The algorithm is quite similar to the last approach. In this approach we consider that there is a global or overall maximum upto a particular element in the array which is maintained by gmax
in our implementation. The cmax
helps us monitor whether the current element should be added to the gmax
or not. Again, dry running the code will make things clearer.
function kadanes_algorithm(arr) {
let gmax = Number.MIN_SAFE_INTEGER;
let cmax = 0;
for (let x of arr) {
cmax += x;
gmax = Math.max(gmax, cmax);
if (cmax < 0) {
cmax = 0;
}
}
return gmax;
}
console.log(kadanes_algorithm([1, 2, 3, -2, 5]));
-> 9
In the next post we will minimize the maximum difference between heights of towers.