Count Largest Group LeetCode

 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.


 


Example 1:


Input: n = 13

Output: 4

Explanation: There are 9 groups in total, they are grouped according sum of its digits of numbers from 1 to 13:

[1,10], [2,11], [3,12], [4,13], [5], [6], [7], [8], [9].

There are 4 groups with largest size.

Example 2:


Input: n = 2

Output: 2

Explanation: There are 2 groups [1], [2] of size 1.



class Solution {
   public int countLargestGroup(int n) {
    // Step 1: Create an array to store the count of each digit sum
    int[] count = new int[37]; // Max digit sum is 9+9+9 = 27 (safe to use 37)

    // Step 2: Loop from 1 to n
    for (int i = 1; i <= n; i++) {
        int sum = digitSum(i);     // calculate digit sum
        count[sum]++;              // increment group size for this sum
    }

    // Step 3: Find the max size among all groups
    int maxSize = 0;
    for (int c : count) {
        if (c > maxSize) {
            maxSize = c;
        }
    }

    // Step 4: Count how many groups have this max size
    int result = 0;
    for (int c : count) {
        if (c == maxSize) {
            result++;
        }
    }

    return result;
}

// Helper function to calculate digit sum
private int digitSum(int num) {
    int sum = 0;
    while (num > 0) {
        sum += num % 10;
        num /= 10;
    }
    return sum;
}

}

Comments

Popular posts from this blog

Two Sum II - Input Array Is Sorted

Comparable Vs. Comparator in Java

Increasing Triplet Subsequence