Approach
Sorting and greedy selection
For Count K-Subsequences of a String With Maximum Beauty Solved, the implementation first exposes a useful order, then scans that order while making locally justified choices.
- Choose the key that reveals the greedy or grouping structure.
- Sort the relevant records by that key.
- Scan in order, maintaining the invariant that makes each local choice safe.
Code notes
- 59 lines of C++ from the credited upstream file 2842.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 5 loop blocks detected.
Complexity
Sorting is typically the dominant term unless the subsequent scan uses a more expensive nested operation.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 int countKSubsequencesWithMaxBeauty(string s, int k) {4 unordered_map<char, int> count;5 for (const char c : s)6 ++count[c];7 if (count.size() < k)8 return 0;9 10 long ans = 1;11 12 for (const auto& [fc, numOfChars] : getFreqCountPairs(count)) {13 if (numOfChars >= k) {14 ans *= nCk(numOfChars, k);15 ans %= kMod;16 return ans * modPow(fc, k) % kMod;17 }18 ans *= modPow(fc, numOfChars);19 ans %= kMod;20 k -= numOfChars;21 }22 23 return ans;24 }25 26 private:27 static constexpr int kMod = 1'000'000'007;28 29 vector<pair<int, int>> getFreqCountPairs(30 const unordered_map<char, int>& count) {31 unordered_map<int, int> freqCount;32 for (const auto& [_, value] : count)33 ++freqCount[value];34 vector<pair<int, int>> freqCountPairs;35 for (const auto& [fc, numOfChars] : freqCount)36 freqCountPairs.emplace_back(fc, numOfChars);37 ranges::sort(freqCountPairs, ranges::greater{},38 [](const pair<int, int>& freqCountPair) {39 return freqCountPair.first;40 });41 return freqCountPairs;42 }43 44 long nCk(int n, int k) {45 long res = 1;46 for (int i = 1; i <= k; ++i)47 res = res * (n - i + 1) / i;48 return res;49 }50 51 long modPow(long x, long n) {52 if (n == 0)53 return 1;54 if (n % 2 == 1)55 return x * modPow(x % kMod, (n - 1)) % kMod;56 return modPow(x * x % kMod, (n / 2)) % kMod;57 }58};59