1399. Count Largest Group #1597
-
Topics: You are given an integer Each number from Return the number of groups that have the largest size. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to group numbers from 1 to n based on the sum of their digits and determine how many groups have the largest size. Approach
Let's implement this solution in PHP: 1399. Count Largest Group <?php
/**
* @param Integer $n
* @return Integer
*/
function countLargestGroup($n) {
$counts = array();
for ($i = 1; $i <= $n; $i++) {
$s = digitSum($i);
if (isset($counts[$s])) {
$counts[$s]++;
} else {
$counts[$s] = 1;
}
}
$max = max($counts);
$result = 0;
foreach ($counts as $cnt) {
if ($cnt == $max) {
$result++;
}
}
return $result;
}
/**
* @param $num
* @return int
*/
function digitSum($num) {
$sum = 0;
while ($num != 0) {
$sum += $num % 10;
$num = (int) ($num / 10);
}
return $sum;
}
// Example usage:
echo countLargestGroup(13); // Output: 4
echo countLargestGroup(2); // Output: 2
?> Explanation:
This approach efficiently groups numbers by their digit sums and then processes these groups to find the required result, ensuring optimal performance even for the upper constraint of n = 10,000. |
Beta Was this translation helpful? Give feedback.
We need to group numbers from 1 to n based on the sum of their digits and determine how many groups have the largest size.
Approach
Let's implement this solution in PHP: 1399. Count Largest Group