fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. long long numOfSubsequences(string s) {
  5. int n = s.length();
  6. if(n == 1) return 0;
  7.  
  8. int l = 0, c = 0, t= 0, lc = 0, ct = 0, lct = 0;
  9. vector<int> prefixL(n);
  10. vector<int> suffixT(n);
  11. for (int i = 0; i < n; i++){
  12. if(s[i] == 'L') {
  13. l++;
  14. }
  15. if(s[i] == 'C'){
  16. lc += l;
  17. c++;
  18. }
  19.  
  20. if(s[i] == 'T'){
  21. lct += lc;
  22. ct += c;
  23. }
  24.  
  25. prefixL[i] = l;
  26. }
  27.  
  28.  
  29.  
  30.  
  31. for (int j = n-1; j >= 0; j--){
  32. if(s[j] == 'T') t++;
  33. suffixT[j] = t;
  34. }
  35.  
  36.  
  37.  
  38. // Case 1 -Inserting 'L' at the front
  39. // ans = old count of "LCT" + total "CT" in the string.
  40. int ans1 = lct + ct;
  41.  
  42.  
  43. // Case 2 - Insering 'T' at the end
  44. // ans = old count of "LCT" + total "LC" in the string.
  45. int ans2 = lct + lc;
  46.  
  47.  
  48. int max1 = max(ans1, ans2);
  49.  
  50. // Case 3 - Inserting 'C' at every position to maximize the count of "LCT"
  51. // Hence there is no need to insert 'C' at first and the end.
  52. int maxc = 0;
  53. for (int k = 0; k < n-1; k++){
  54. int temp = prefixL[k] * suffixT[k+1];
  55. maxc = max(maxc, temp);
  56. }
  57.  
  58. int ans3 = lct + maxc;
  59.  
  60. return max(ans3, max1);
  61. }
  62.  
  63. int main() {
  64. // your code goes here
  65.  
  66. string s = "LCLPTTGC";
  67. cout << numOfSubsequences(s);
  68.  
  69. return 0;
  70. }
Success #stdin #stdout 0.01s 5292KB
stdin
Standard input is empty
stdout
6