Approach
Sorting and greedy selection
For Sum of Largest Prime Substrings, 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
- 32 lines of C++ from the credited upstream file 3556.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 3 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 long long sumOfLargestPrimes(string s) {4 const int n = s.length();5 unordered_set<long> primes;6 7 for (int i = 0; i < n; ++i)8 for (int j = i + 1; j <= n; ++j) {9 const long num = stol(s.substr(i, j - i));10 if (!primes.contains(num) && isPrime(num))11 primes.insert(num);12 }13 14 vector<long> sortedPrimes{primes.begin(), primes.end()};15 ranges::sort(sortedPrimes, greater<>());16 return accumulate(17 sortedPrimes.begin(),18 sortedPrimes.begin() + min(3, static_cast<int>(sortedPrimes.size())),19 0L);20 }21 22 private:23 bool isPrime(long num) {24 if (num <= 1)25 return false;26 for (int i = 2; i <= sqrt(num); ++i)27 if (num % i == 0)28 return false;29 return true;30 }31};32