Computer >> Computer tutorials >  >> Programming >> Javascript

Largest sum of subarrays in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of non-negative integers, arr, as the first argument and an Integer, num, (num < arr.length) as the second argument.

The task of our function is to split the array into num non-empty continuous subarrays. The array should be splitted in such a way that it minimizes the largest sum among these num subarrays. Our function should then return the largest sum accumulated among the subarray.

For example, if the input to the function is −

const arr = [5, 1, 4, 8, 7];
const num = 2;

Then the output should be −

const output = 15;

Output Explanation

Although there are four ways to split the original array into subarrays but if we split the array into two groups [5, 1, 4] and [8, 7] then these two groups will have the smallest sums and the larger of these two is 8 + 7 = 15 which our function should return.

Example

The code for this will be −

const arr = [5, 1, 4, 8, 7];
const num = 2;
const splitArray = (arr = [], num = 1) => {
   let max = 0;
   let sum = 0;
   const split = (arr, mid) => {
      let part = 1;
      let tempSum = 0;
      for (let num of arr) {
         if (tempSum + num > mid) {
            tempSum = num;
            part++;
         } else {
            tempSum += num;
         }
      }
      return part;
   };
   for (let num of arr) {
      max = Math.max(max, num);
      sum += num;
   };
   let low = max;
   let high = sum;
   while (low < high) {
      let mid = Math.floor((high+low)/2);
      let part = split(arr, mid);
      if (part > num) {
         low = mid + 1;
      } else {
         high = mid;
      }
   }
   return low;
};
console.log(splitArray(arr, num));

Code Explanation:

We have here used Binary Search to check if we can find best split.

Output

The output in the console will be −

15