Adding elements to array to make its sum diverse in JavaScript

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.

Problem Example

For example, if the input to the function is:

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

Then the output should be:

2

Output Explanation

Because if we add two numbers, (2 and 4) to the array, we can achieve any sum between [0, 20]. The original array [1, 5, 10] combined with added elements [2, 4] gives us [1, 2, 4, 5, 10], which can form any sum from 0 to 20.

Algorithm Approach

The algorithm uses a greedy approach:

  • Sort the array to process elements in ascending order
  • Track the maximum sum we can currently achieve (canAdd)
  • If there's a gap in our coverage, add the smallest possible number to fill it
  • Continue until we can form all sums up to the target

Implementation

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

const minimumAddition = (arr = [], sum = 1) => {
    // Sort array to process elements in ascending order
    arr.sort((a, b) => a - b);
    
    let canAdd = 1;  // Maximum sum we can currently achieve + 1
    let count = 0;   // Number of elements we need to add
    let i = 0;       // Index for array traversal
    
    while (canAdd <= sum) {
        // If we've used all elements or current element is too large
        if (i >= arr.length || canAdd < arr[i]) {
            // Add the missing number (canAdd) to fill the gap
            count++;
            canAdd += canAdd; // Double our range
        } else {
            // Use the current array element
            canAdd += arr[i++];
        }
    }
    
    return count;
};

console.log("Array:", arr);
console.log("Target sum:", sum);
console.log("Minimum additions needed:", minimumAddition(arr, sum));
Array: [ 1, 5, 10 ]
Target sum: 20
Minimum additions needed: 2

Step-by-Step Execution

const minimumAdditionDetailed = (arr = [], sum = 1) => {
    arr.sort((a, b) => a - b);
    console.log("Sorted array:", arr);
    
    let canAdd = 1;
    let count = 0;
    let i = 0;
    
    while (canAdd <= sum) {
        console.log(`Step: canAdd=${canAdd}, i=${i}, current element=${arr[i] || 'none'}`);
        
        if (i >= arr.length || canAdd < arr[i]) {
            console.log(`Adding ${canAdd} to fill gap`);
            count++;
            canAdd += canAdd;
        } else {
            console.log(`Using existing element ${arr[i]}`);
            canAdd += arr[i++];
        }
        
        console.log(`Now can form sums 0 to ${canAdd - 1}<br>`);
    }
    
    return count;
};

minimumAdditionDetailed([1, 5, 10], 20);
Sorted array: [ 1, 5, 10 ]
Step: canAdd=1, i=0, current element=1
Using existing element 1
Now can form sums 0 to 1

Step: canAdd=2, i=1, current element=5
Adding 2 to fill gap
Now can form sums 0 to 3

Step: canAdd=4, i=1, current element=5
Adding 4 to fill gap
Now can form sums 0 to 7

Step: canAdd=8, i=1, current element=5
Using existing element 5
Now can form sums 0 to 12

Step: canAdd=13, i=2, current element=10
Using existing element 10
Now can form sums 0 to 22

2

How It Works

The algorithm maintains the invariant that we can form any sum from 0 to (canAdd - 1). When we encounter a gap, we add the smallest number that extends our range optimally. This greedy approach ensures the minimum number of additions.

Conclusion

This solution efficiently finds the minimum elements needed to make an array capable of forming any sum in a given range. The greedy approach ensures optimal results by always adding the smallest number that maximally extends our coverage.

Updated on: 2026-03-15T23:19:00+05:30

176 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements