-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy path1399-count-largest-group.js
More file actions
43 lines (38 loc) · 880 Bytes
/
1399-count-largest-group.js
File metadata and controls
43 lines (38 loc) · 880 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* 1399. Count Largest Group
* https://leetcode.com/problems/count-largest-group/
* Difficulty: Easy
*
* You are given an integer n.
*
* Each number from 1 to n is grouped according to the sum of its digits.
*
* Return the number of groups that have the largest size.
*/
/**
* @param {number} n
* @return {number}
*/
var countLargestGroup = function(n) {
const map = new Map();
let maxSize = 0;
for (let num = 1; num <= n; num++) {
const digitSum = calculateDigitSum(num);
const size = (map.get(digitSum) || 0) + 1;
map.set(digitSum, size);
maxSize = Math.max(maxSize, size);
}
let result = 0;
for (const size of map.values()) {
if (size === maxSize) result++;
}
return result;
};
function calculateDigitSum(num) {
let sum = 0;
while (num > 0) {
sum += num % 10;
num = Math.floor(num / 10);
}
return sum;
}