Using Kadane’s algorithm to find maximum sum of subarray in JavaScript


Exploring sophisticated algorithms is key to unlocking the true potential of JavaScript programming, particularly when it comes to solving complex computational challenges. Among these algorithms, Kadane's algorithm stands out as a formidable tool for efficiently finding the maximum sum of subarrays within an array. This remarkable technique allows developers to optimize their code and enhance the performance of their applications when dealing with large data sets. In this article, we delve into the intricacies of Kadane's algorithm, unveiling its inner workings and showcasing its efficacy in tackling the task of identifying the maximum sum of subarrays in JavaScript. By grasping the underlying principles and implementing this algorithm in practice, developers can elevate their programming skills and conquer the realm of computational problem-solving.

Problem Statement

Implement Kadane's algorithm in JavaScript to find the maximum sum of a subarray in a given array.

Sample Input −

arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]

Sample Output −

The maximum sum of a subarray in the given array is 6. The subarray with the maximum sum is [4, -1, 2, 1].

Approach

In this article, we are going to see a number of different ways to solve the above problem statement in JavaScript −

  • Naïve Approach

  • Kadane's Algorithm (Dynamic Programming

  • Kadane's Algorithm with Indices

Method 1: Naïve Approach

To find the maximum sum of a subarray, the naive approach initializes maxSum as -Infinity and iterates over each index i, representing the starting index of the subarray. For each starting index i, it iterates from i to the end of the array, representing the ending index of the subarray. The sum of the current subarray is calculated, and if it is greater than maxSum, maxSum is updated. Finally, the final maxSum is returned after both loops complete.

Example

In the given code, the variable maxSum is initially set to -Infinity to ensure that any positive sum encountered will be considered as the new maximum. The outer loop goes through each index i of the array, indicating the starting index of the subarray. The inner loop iterates from the starting index i to the end of the array, representing the ending index of the subarray. During each iteration of the inner loop, the variable sum keeps track of the sum of the current subarray. The maximum sum is updated by comparing the current maximum sum with the sum of the current subarray using Math.max(maxSum, sum). Finally, after both loops complete, the final maximum sum is returned.

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)}`);

Output

The following is the console output −

Maximum Sum: 6

Method 2: Kadane's Algorithm (Dynamic Programming

Kadane's Algorithm is a dynamic programming approach used to find the maximum subarray sum in an array. It starts by initializing two variables, maxEndingHere and maxSoFar, to 0 and -Infinity, respectively. Then, it iterates through each index i of the array, updating maxEndingHere by comparing the current element arr[i] and the sum of the previous subarray ending at i-1 plus the current element. The algorithm also updates maxSoFar by comparing the current maxSoFar and maxEndingHere. Finally, after the loop completes, the algorithm returns the final maxSoFar as the maximum subarray sum.

Example

In the provided code, the initial values of maxEndingHere and maxSoFar are set to 0 and -Infinity respectively. A loop is implemented to iterate through each index i of the array. Within each iteration, maxEndingHere is updated using Math.max(arr[i], maxEndingHere + arr[i]). This comparison determines whether extending the current subarray (by adding arr[i]) would result in a larger sum or if starting a new subarray from arr[i] would yield a larger sum. To ensure that maxSoFar always stores the maximum sum found so far, it is updated by comparing the current maxSoFar with maxEndingHere using Math.max(maxSoFar, maxEndingHere). Finally, once the loop is complete, the final maximum sum (maxSoFar) is returned.

function maxSubarraySum(arr) {
   let maxEndingHere = 0;
   let maxSoFar = -Infinity;

   for (let i = 0; i < arr.length; i++) {
      maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);
      maxSoFar = Math.max(maxSoFar, maxEndingHere);
   }
   return maxSoFar;
}
const arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
console.log(`Maximum Sum: ${maxSubarraySum(arr)}`);

Output

The following is the console output −

Maximum Sum: 6

Method 3: Kadane's Algorithm with Indices

Kadane's Algorithm is a technique that finds the maximum sum of a subarray in an array. It involves initializing variables such as maxEndingHere, maxSoFar, start, end, and tempStart. By iterating through each index of the array, the algorithm compares whether extending the current subarray (by adding the value at arr[i]) produces a larger sum than starting a new subarray from arr[i]. If extending the subarray is more advantageous, maxEndingHere and tempStart are updated accordingly. The algorithm also updates maxSoFar, start, and end based on the maximum sum found and their respective indices. Ultimately, the algorithm returns an object with the maximum sum and its corresponding subarray.

Example

In the given code, variables such as maxEndingHere, maxSoFar, start, end, and tempStart are initialized similarly as before. A loop iterates over each index i of the array. Inside the loop, an if statement compares the sum of extending the current subarray (by adding arr[i]) with starting a new subarray from arr[i]. If the extension yields a larger sum, maxEndingHere and tempStart are updated. The maximum sum and corresponding indices are updated in the same manner as before. Finally, the function returns an object with properties maxSum (representing the maximum sum) and subarray (representing the corresponding subarray).

function maxSubarraySum(arr) {
   let maxEndingHere = 0;
   let maxSoFar = -Infinity;
   let start = 0;
   let end = 0;
   let tempStart = 0;

   for (let i = 0; i < arr.length; i++) {
      if (arr[i] > maxEndingHere + arr[i]) {
         tempStart = i;
         maxEndingHere = arr[i];
      } else {
         maxEndingHere += arr[i];
      }

      if (maxEndingHere > maxSoFar) {
         start = tempStart;
         end = i;
         maxSoFar = maxEndingHere;
      }
   }

   return {
      maxSum: maxSoFar,
      subarray: arr.slice(start, end + 1)
   };
}
 
const arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4];
const res = maxSubarraySum(arr);
console.log(`Maximum Sum: ${res.maxSum}`);
console.log(`Maximum Sum Subarray: ${res.subarray}`);

Output

The following is the console output −

Maximum Sum: 6
Maximum Sum Subarray: 4,-1,2,1

Conclusion

In culmination, the utilization of Kadane's algorithm to ascertain the maximum sum of subarrays in JavaScript can be a prodigious technique for enhancing efficiency and optimizing computational resources. By employing this esoteric algorithm, developers can unlock a hidden reservoir of potential, unraveling intricate data patterns and extracting valuable insights. Implementing this algorithm may require a certain level of acumen, but the rewards are manifold: accelerated performance, streamlined operations, and unparalleled precision in identifying the most substantial subarray sums. In conclusion, the esoteric prowess of Kadane's algorithm empowers JavaScript programmers to transcend conventional boundaries and unlock the true potential of their applications.

Updated on: 04-Aug-2023

260 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements