# Adding elements to array to make its sum diverse in JavaScript

## 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 count = 0,i = 0;
if((i >= arr.length) || (canAdd < arr[i])){
count++;
}else{
};
};
return count;
};
console.log(minimumAddition(arr, sum));

## Output

The output in the console will be −

2

Updated on: 19-Mar-2021

37 Views