- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
- Related Articles
- Subarrays product sum in JavaScript
- Binary subarrays with desired sum in JavaScript
- Sum of All Possible Odd Length Subarrays in JavaScript
- JavaScript Total subarrays with Sum K
- Finding n subarrays with equal sum in JavaScript
- Sum of XOR of all subarrays in C++
- Largest rectangle sum smaller than num in JavaScript
- Binary Subarrays With Sum in C++
- Merging subarrays in JavaScript
- Maximum Sum of 3 Non-Overlapping Subarrays in C++
- Find number of subarrays with even sum in C++
- Maximum Sum of Two Non-Overlapping Subarrays in C++
- Count subarrays with Prime sum in C++
- Find all subarrays with sum equal to number? JavaScript (Sliding Window Algorithm)
- Largest Sum of Averages in C++
