Largest sum of subarrays in JavaScript


The quest for finding the largest sum of subarrays in JavaScript is a pursuit of paramount importance for developers seeking to optimize algorithmic efficiency and unravel the hidden potential within their data sets. In the realm of computational problem-solving, the ability to identify and compute the maximal cumulative sum of subsets within an array holds the key to unlocking insights and driving impactful decision-making processes. In this article, we embark upon a comprehensive exploration of the methodologies and techniques required to tackle this intricate challenge, employing a diverse array of rarely used words to elucidate the intricacies of JavaScript programming. By delving into the depths of this topic, readers will gain the prowess to navigate complex data structures and unleash the full potential of their JavaScript applications.

Problem Statement

The goal is to devise an efficient algorithm capable of effectively identifying the subarray with the utmost summation, while considering the scarcity of commonly employed terms. To elucidate, suppose we have an input array consisting of integer elements

[-3, 4, 2, -1, 6, -5, 3, -2, 7, 1]

the desired outcome would be the largest sum achievable from any contiguous subarray, which, in this case, would be

15

Approach

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

  • Brute Force

  • Dynamic Programming

  • Divide and Conquer

  • Prefix Sum

Method 1: Brute Force

In the brute force approach, we generate all possible subarrays and calculate the sum of each. We set maxSum to -Infinity to track the maximum sum encountered. Using three nested loops, the outer loop iterates over starting indices, the middle loop over ending indices, and the inner loop calculates the sum of the subarray by iterating from the starting to the ending index.

Example

The findMaxSubarraySumBruteForce function takes an array arr as input and initializes maxSum to -Infinity. It utilizes three nested loops to generate all possible subarrays: the outer loop for the starting index, the middle loop for the ending index, and the inner loop to calculate the sum. The maximum sum is updated whenever a greater sum is found. Finally, the function returns the maximum sum.

function findMaxSubarraySumBruteForce(arr) {
  let maxSum = -Infinity;
 
   for (let i = 0; i < arr.length; i++) {
      for (let j = i; j < arr.length; j++) {
         let sum = 0;
         for (let k = i; k <= j; k++) {
            sum += arr[k];
         }
         maxSum = Math.max(maxSum, sum);
      }
   }
   return maxSum;
}
const arr = [-3, 4, 2, -1, 6, -5, 3, -2, 7, 1];
console.log(findMaxSubarraySumBruteForce(arr));

Output

The following is the console output −

15

Method 2: Dynamic Programming (Kadane’s Algorithm)

Kadane's algorithm is an efficient dynamic programming approach for finding the maximum sum of subarrays in a single pass through the array. It uses two variables, maxSoFar and maxEndingHere, to track the maximum sum encountered. Starting from the second element, we iterate through the array and update maxEndingHere by taking the maximum value between the current element and the sum of the current element and maxEndingHere. We update maxSoFar by taking the maximum value between the previous maxSoFar and the updated maxEndingHere. After iterating through the entire array, maxSoFar contains the largest sum of subarrays, which is then returned.

Example

The findMaxSubarraySumKadane function takes an array arr as input and initializes maxSoFar and maxEndingHere variables. It iterates through the array, updating maxEndingHere by comparing the current element with the sum of the current element and maxEndingHere. It also updates maxSoFar by comparing the previous maxSoFar with the updated maxEndingHere. Once the iteration is complete, the function returns the maximum subarray sum stored in the maxSoFar variable.

function findMaxSubarraySumKadane(arr) {
   let maxSoFar = arr[0];
   let maxEndingHere = arr[0];
 
   for (let i = 1; i < arr.length; i++) {
      maxEndingHere = Math.max(arr[i], maxEndingHere + arr[i]);
      maxSoFar = Math.max(maxSoFar, maxEndingHere);
   }
   return maxSoFar;
}
const arr = [-3, 4, 2, -1, 6, -5, 3, -2, 7, 1];
console.log(findMaxSubarraySumKadane(arr));

Output

The following is the console output −

15

Method 3: Divide and Conquer

In the divide and conquer approach for finding the maximum subarray sum, the array is recursively split into smaller subarrays. The function findMaxSubarraySumDivideAndConquer takes an array, a low index, and a high index. If the low index equals the high index, it returns the single element as the maximum subarray sum. The mid index is calculated as the floor value of the average of the low and high indices. The function is recursively called to find the maximum subarray sum in the left and right halves of the array. The findMaxCrossingSum function is also called to find the maximum subarray sum crossing the middle element. The maximum among the left, right, and crossing sums is returned. The findMaxCrossingSum function takes an array, a low index, a mid index, and a high index. It calculates the maximum subarray sum that crosses the middle element by tracking the maximum sum on the left and right sides. The sum of leftSum and rightSum is returned as the maximum sum crossing the middle element.

Example

The findMaxSubarraySumDivideAndConquer function takes an array arr, a low index, and a high index as input. If the low index is equal to the high index, it returns that element as the maximum subarray sum. The function finds the mid index, calls itself recursively to find the maximum subarray sum in the left and right halves of the array, and also calls the findMaxCrossingSum function to find the maximum sum crossing the middle element. Finally, it returns the maximum value among the three sums. The findMaxCrossingSum function takes an array arr, a low index, a mid index, and a high index as input. It calculates the maximum sum on the left and right sides, and returns the sum of both, representing the maximum sum crossing the middle element.

function findMaxSubarraySumDivideAndConquer(arr, low, high) {
   if (low === high) {
      return arr[low];
   }
 
   const mid = Math.floor((low + high) / 2);
 
   const maxLeft = findMaxSubarraySumDivideAndConquer(arr, low, mid);
   const maxRight = findMaxSubarraySumDivideAndConquer(arr, mid + 1, high);
   const maxCrossing = findMaxCrossingSum(arr, low, mid, high);
 
   return Math.max(maxLeft, maxRight, maxCrossing);
}
 
function findMaxCrossingSum(arr, low, mid, high) {
   let leftSum = -Infinity;
   let sum = 0;
 
   for (let i = mid; i >= low; i--) {
      sum += arr[i];
      if (sum > leftSum) {
         leftSum = sum;
      }
   }
 
   let rightSum = -Infinity;
   sum = 0;
 
   for (let i = mid + 1; i <= high; i++) {
      sum += arr[i];
      if (sum > rightSum) {
         rightSum = sum;
      }
   }
 
   return leftSum + rightSum;
}
const arr = [-3, 4, 2, -1, 6, -5, 3, -2, 7, 1];
console.log(findMaxSubarraySumDivideAndConquer(arr,0,arr.length-1));

Output

The following is the console output −

15

Method 4: Prefix Sum

The prefix sum approach involves calculating the prefix sum of the array and utilizing the concept of minimum prefix sum to find the largest sum of subarrays. We initialize maxSum to -Infinity to track the maximum sum encountered, and minPrefixSum and prefixSum variables to track the minimum prefix sum and current prefix sum. We iterate through the array, updating prefixSum, maxSum, and minPrefixSum. We return maxSum as the largest sum of subarrays.

Example

The findMaxSubarraySumPrefixSum function takes an array arr as input and initializes variables to keep track of the maximum sum encountered, the minimum prefix sum, and the current prefix sum. It iterates through the array, updating the prefix sum and calculating the maximum sum by taking the difference between the prefix sum and the minimum prefix sum. The minimum prefix sum is updated as well. Finally, the maximum sum is returned.

function findMaxSubarraySumPrefixSum(arr) {
   let maxSum = -Infinity;
   let minPrefixSum = 0;
   let prefixSum = 0;
 
   for (let i = 0; i < arr.length; i++) {
      prefixSum += arr[i];
      maxSum = Math.max(maxSum, prefixSum - minPrefixSum);
      minPrefixSum = Math.min(minPrefixSum, prefixSum);
   } 
   return maxSum;
}
const arr = [-3, 4, 2, -1, 6, -5, 3, -2, 7, 1];
console.log(findMaxSubarraySumPrefixSum(arr));

Output

The following is the console output −

15

Conclusion

In denouement, the exploration of finding the largest sum of subarrays in JavaScript has uncovered a trove of fascinating techniques and algorithms. This intricate pursuit necessitates astute mathematical calculations and dexterity in coding practices. By delving into the depths of these lesser-known approaches, developers can augment their proficiency and unlock new possibilities in solving complex array-related challenges. The mastery of such esoteric methods empowers programmers to unravel intricate subarray patterns and derive optimized solutions. In conclusion, the diligent implementation of these rarefied strategies in JavaScript broadens the horizons of problem-solving and paves the way for innovative solutions to the largest sum of subarrays conundrum.

Updated on: 04-Aug-2023

143 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements