Given an integer
Return how many groups have the largest size.
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
Approach
Java
public class CountLargestGroup {public static void main(String[] args) {int n = 13;System.out.println(countLargestGroup(n));}static int countLargestGroup(int n) {int[] freqs = new int[1001];int max = 0;int ca = 0;for (int i = 1; i <= n; i++) {int sum = sumOfDigits(i);if (freqs[sum] + 1 > max) {ca = 1;max = freqs[sum] + 1;} else if (freqs[sum] + 1 == max) {ca++;}freqs[sum]++;}return ca;}static int sumOfDigits(int n) {if (n <= 9)return n;int sum = 0;while (n > 0) {sum += n % 10;n /= 10;}return sum;}}
C++
#include <bits/stdc++.h>using namespace std;int countLargestGroup(int n){int sum[n];if (n == 1)return 1;for (int i = 0; i < n; i++)sum[i] = 0;for (int i = 1; i <= n; i++){int j = i, l = i - 1;while (j){sum[l] += j % 10;j = j / 10;}}vector<int> vec;sort(sum, sum + n);for (int i = 0; i < n - 1; i++){int cnt = 1;while (i < n - 1 && sum[i] == sum[i + 1]){cnt++;i++;}vec.push_back(cnt);}if (sum[n - 1] != sum[n - 2])vec.push_back(1);sort(vec.begin(), vec.end());int cnt = 0;for (int i = vec.size() - 1; i >= 0; i--)if (vec[i] == vec[vec.size() - 1])cnt++;elsebreak;return cnt;}int main(){int n = 13;cout << countLargestGroup(n);return 0;}
No comments:
Post a Comment