We are required to write a JavaScript function that takes in a positive integer, say n, as the only argument.
The function should first group the integers from 1 to n to subarray where a specific subarray contains all the elements contains a specific digit sum. Then the function should examine each subarray and return the length of that subarray which contains the most elements.
For example −
If the input number is −
const num = 15;
Then the output should be −
const output = 2;
because the groups are −
[1, 10], [2, 11], [3, 12], [4, 13], [5, 14], [6, 15], [7], [8], [9]
Example
Following is the code −
const num = 67;
const countLargestGroup = (num = 1) => {
if(num < 10){
return num;
};
let res = 0;
let temp = 0;
let map = {};
for(let i = 1; i <= num; i++){
let sum = 0;
let num = i;
while (num) {
sum += num % 10;
num = Math.floor(num / 10);
}
if(map[sum] != undefined){
map[sum]++;
} else {
map[sum] = 1;
}
};
for (const key of Object.keys(map)) {
if(temp == map[key]){
res++;
}
else if(temp < map[key]){
res = 1;
temp = map[key];
}
};
return res;
};
console.log(countLargestGroup(num));Output
Following is the console output −
4