1399_Count Largest Group

Link: https://leetcode.com/problems/count-largest-group/

Given an integer n. Each number from 1 to n is grouped according to the sum of its digits.

Return how many groups 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.

Example 3:

Input: n = 24
Output: 5

Constraints:

  • 1 <= n <= 10^4

題目翻譯:

給定一個 n,然後將 1~n 進行分組,分組的方法就是,數字

程式思路:

很 easy

class Solution {
private:
    int digits_sum(int input)
    {
        int sum = 0;
        while (input/10 != 0)
        {
            sum += input %10;
            input/=10;
        }
        sum += input %10;
        return sum;
    }
public:
    int countLargestGroup(int n) {
        vector <int> count(36,0); // max 1~9999 = 1 ~ 36
        for(int i = 1; i <= n; i++)
        {
            count[digits_sum(i)-1]++;
        }
        int maxi = *max_element(count.begin(),count.end());
        return count_if(begin(count), end(count), [&maxi](const auto &p) {return p == maxi;});
    }
};

  轉載請註明: YuYan's blog 1399_Count Largest Group

  目錄