Adding elements to array to make its sum diverse in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in an array of Numbers, arr, as the first argument and a single number, num, as the second argument.

We should, by adding elements to it, make our array such that any sum can be obtained by adding specific numbers from it between [0, num] (including both). Our function should finally return the minimum number of numbers required to add to the array so that it can produce any sum between 0 and num.

For example, if the input to the function is −

const arr = [1, 5, 10];
const sum = 20;

Then the output should be −

const output = 2;

Output Explanation:

Because if we add two number, (2 and 4) to the array, we can achieve any sum between [0, 20]

Example

The code for this will be −

const arr = [1, 5, 10];
const sum = 20;
const minimumAddition = (arr = [], sum = 1) => {
   let canAdd = 1;
   let count = 0,i = 0;
   while(canAdd <= sum){
      if((i >= arr.length) || (canAdd < arr[i])){
         count++;
         canAdd+=canAdd;
      }else{
         canAdd += arr[i++];
      };
   };
   return count;
};
console.log(minimumAddition(arr, sum));

Output

The output in the console will be −

2
raja
Updated on 19-Mar-2021 06:10:49

Advertisements