- Translate each rule into one explicit state update.
- Maintain the invariant after every processed item.
- Return the accumulated state once all relevant input has been handled.
Code notes
- 49 lines of C++ from the credited upstream file 1531.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Count the number and nesting of passes over the input, then include the maintained containers in the memory estimate.
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 getLengthOfOptimalCompression(string s, int k) {4 vector<vector<int>> mem(s.length(), vector<int>(k + 1, kMax));5 return compression(s, 0, k, mem);6 }7 8 private:9 static constexpr int kMax = 101;10 11 12 13 int compression(const string& s, int i, int k, vector<vector<int>>& mem) {14 if (k < 0)15 return kMax;16 if (i == s.length() || s.length() - i <= k)17 return 0;18 if (mem[i][k] != kMax)19 return mem[i][k];20 21 int maxFreq = 0; 22 vector<int> count(128);23 24 25 26 27 for (int j = i; j < s.length(); ++j) {28 maxFreq = max(maxFreq, ++count[s[j]]);29 mem[i][k] = min( 30 mem[i][k], 31 getLength(maxFreq) +32 compression(s, j + 1, k - (j - i + 1 - maxFreq), mem));33 }34 35 return mem[i][k];36 }37 38 39 int getLength(int maxFreq) {40 if (maxFreq == 1)41 return 1; 42 if (maxFreq < 10)43 return 2; 44 if (maxFreq < 100)45 return 3; 46 return 4; 47 }48};49