- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
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 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
Advertisements