We are asked: given a string S consisting only of uppercase letters 'C', 'H', 'E', 'F'. In one move, we take a subsequence (not necessarily contiguous) that spells "CHEF" and remove those symbols from the string. The goal is to maximize the number of moves. Find the maximal number of moves.
We need to find the maximum number of disjoint subsequences "CHEF" we can extract from S. This is essentially the maximum number of times we can pick "C" then later "H" then later "E" then later "F", removing them as we go. Equivalent to: given a sequence of characters, we want to partition as many as possible into groups that are exactly "CHEF" in order (but not necessarily contiguous). It's a resource allocation problem: we have a multiset of letters, but order matters because we need subsequence ordering. We want to maximize number of complete "CHEF" sequences in order.
This is similar to counting the number of times we can form "CHEF" as a subsequence with non-overlapping letters. Equivalent to: we can greedily match as many as possible? Typically, for maximizing number of disjoint subsequences of a pattern, a greedy approach from left to right works? But careful: pattern "CHEF", we need to use each character at most once. We want to maximize count. It is a classic problem: maximum number of non-overlapping subsequences equal to a given word can be solved by repeatedly finding the earliest occurrence of the pattern and removing, or using a greedy algorithm: scan left to right, maintain counts of partial matches? Actually, it's like we have to allocate letters to as many full patterns as possible. This is similar to a flow problem: we have positions with characters, we need to assign them to patterns in order. Because the pattern length is small (4), we can do a DP.
Alternatively, we can think of it as: we want to maximize the number of quadruples (i1 < i2 < i3 < i4) with S[i1]='C', S[i2]='H', S[i3]='E', S[i4]='F', each index used at most once. This is a maximum matching in a bipartite chain? Actually, we can treat it as a maximum set of vertex-disjoint increasing sequences following pattern.
One standard method: greedily match as many patterns as possible by scanning and whenever we complete a pattern, increment count and reset. But does that yield optimal? Consider S = "C H H E E F". Actually: "CHHEEF". If we greedily match earliest possible: first C at pos1, then H at pos2, then E at pos3? But pos3 is H? Actually "CHHEEF": positions: 1:C,2:H,3:H,4:E,5:E,6:F. Greedy: match C(1), then earliest H after 1 is pos2, then earliest E after 2 is pos4, then earliest F after 4 is pos6 => we form one pattern using indices 1,2,4,6. After removal, leftover: pos3:H, pos5:E. No further pattern. So count=1. Could there be 2? Need two "CHEF" patterns: we would need two C, two H, two E, two F. We have only one C and one F, so max is 1. So greedy works.
But consider case where greedy might fail? Suppose we have multiple Cs, Hs, Es, Fs. We want to maximize number of patterns. This is similar to the problem of maximum number of disjoint subsequences "AB" in a string, which can be solved by counting: we can match greedily from left: for each 'B', we need a preceding 'A', the maximum number of pairs is min(count(A), count(B)), but ordering also matters: we need A before B. Actually for pattern "AB", the maximum number of disjoint subsequences is the maximum number of pairs with A before B, which equals: we can compute by scanning and using a counter: when see A, increment available A; when see B and available A > 0, then pair one, increment count, decrement available A. This greedy yields the maximum.
For longer patterns, we can extend this idea: we can treat as building patterns incrementally. We can maintain counts of partial patterns: number of "C" that are not yet matched, number of "CH" (i.e., sequences that have seen C and H in order), number of "CHE", etc. As we scan left to right, we update. At the end, the number of full patterns is the count of "CHEF" completed.
But careful: if we just greedily match as soon as possible, does that guarantee maximum total? Let's think: for pattern "ABC", we can maintain three counters: countA, countAB, countABC. When we see 'A', we increment countA. When we see 'B', if countA > 0, we can convert one A to AB: decrement countA, increment countAB. When we see 'C', if countAB > 0, decrement countAB, increment countABC. This greedy algorithm yields maximum number of "ABC" subsequences. I recall this is correct for any fixed pattern because it's essentially a flow network with greedy property? It is similar to maximum number of non-overlapping subsequences; it's the solution to the "Maximum number of pattern matches" problem known as "string packing" or "disjoint subsequences". For a pattern of length k, scanning left to right and greedily matching at the earliest opportunity yields the maximum number of disjoint subsequences, because it's like a matroid? I think it's true for patterns where the characters are distinct? Not exactly; but I've seen problems: "Maximum number of subsequences equal to 'ab' in a string", "Maximum number of subsequences equal to 'abc'", etc. The greedy algorithm of taking the leftmost possible matches yields the maximum count. More formally, it's equivalent to computing the maximum cardinality of a set of disjoint occurrences; there is a known greedy algorithm: repeatedly remove the leftmost occurrence of the pattern (i.e., find the smallest indices that form the pattern) and count. Since the pattern is fixed and the matches are non-overlapping, removing the leftmost occurrence doesn't reduce the potential for other matches. This is analogous to scheduling intervals: for sequences, the greedy algorithm that picks the earliest finishing time works for interval scheduling but here it's about subsequences. There is a known result: the maximum number of disjoint subsequences equal to a given word can be obtained by repeatedly choosing the leftmost possible occurrence (or equivalently, by the algorithm that maintains counts for prefixes). I think it's correct.
Let's test on a tricky case. Pattern "ABAB". Suppose S = "A B A B". If we greedily: we see first A at pos1, then earliest B after is pos2 => we have "AB"? But we need full "ABAB". Actually algorithm: maintain counts for "A", "AB", "ABA", "ABAB". Let's simulate:
- pos1: 'A': countA=1
- pos2: 'B': since countA>0, countA--, countAB=1
- pos3: 'A': can we use it to extend countAB? Usually algorithm for pattern "ABAB": when we see 'A', we might want to start a new pattern or extend an existing "AB" to "ABA"? Actually pattern is "ABAB": after we have "AB", next needed is 'A' to get "ABA". So on seeing 'A', if there is any "AB" waiting, we can convert one to "ABA". Also we could start a new "A". So we need to decide which to do: maybe it's better to start a new 'A' rather than extend an existing "AB"? But the greedy approach of always extending when possible yields the maximum? Let's test.
We'll simulate two possible strategies:
- Greedy: on 'A', we increment countA; on 'B', if countA>0, we decrement countA and increment countAB; on 'A', if countAB>0, we decrement countAB and increment countABA; on 'B', if countABA>0, we decrement countABA and increment countABAB.
But careful: pattern "ABAB": sequence: first 'A', then 'B', then 'A', then 'B'. So states: after seeing some characters, we have partial matches:
state0: want 'A'
state1: have 'A', want 'B'
state2: have 'AB', want 'A'
state3: have 'ABA', want 'B'
In scanning left to right, we maintain counts for each state. When we see a character, we can transition from a state that expects that character to the next state. Specifically:
- On seeing 'A': we can take a state0 (i.e., start a new pattern) and move to state1? Actually state0 is "want A". If we have count0 (number of patterns waiting for 'A'), then we can convert them to state1. But also we can start a new pattern? Starting a new pattern is essentially taking from an infinite supply of "empty patterns"? We need to model that we can always start a new pattern at any time. Typically, algorithm: we have a counter for each prefix length that we have formed so far. When we see a character, we try to extend the longest possible? Actually standard algorithm: For each character, we update counts in order of decreasing prefix length to avoid using the same character multiple times. For pattern "ABAB", we could do:
Let cnt[0] = INF (or we treat starting new pattern as always possible). But typical implementation: maintain an array dp[i] meaning number of patterns that have matched the first i characters (i.e., prefix of length i) so far. Initially dp[0] = infinity (or a large number representing we can start as many as we want). But actually we have a limited number of characters; we can start a new pattern only when we encounter an 'A', but we can decide to not start it. The usual greedy algorithm for maximizing number of occurrences of a pattern as a subsequence (not disjoint) just matches greedily from left yields one occurrence; that's different.
For maximum number of disjoint occurrences, we need to allocate characters. There is known solution using DP with greedy: For pattern length L, we iterate through string, and for each character, we try to extend partial matches from the last needed character backwards. We maintain an array need[4] or something. Actually I recall a known solution: To count maximum number of non-overlapping subsequences equal to "CHEF", we can do:
Initialize count_C = count_CH = count_CHE = 0. For each character c in S:
if c == 'C': count_C += 1
elif c == 'H': if count_C > 0: count_C--; count_CH += 1
elif c == 'E': if count_CH > 0: count_CH--; count_CHE += 1
elif c == 'F': if count_CHE > 0: count_CHE--; answer += 1
This yields the answer. Let's test on example:
S = "CHEFCHEFFFF"
Iterate:
1 C: count_C=1
2 H: count_C>0 => count_C=0, count_CH=1
3 E: count_CH>0 => count_CH=0, count_CHE=1
4 F: count_CHE>0 => count_CHE=0, ans=1
5 C: count_C=1
6 H: count_C>0 => count_C=0, count_CH=1
7 E: count_CH>0 => count_CH=0, count_CHE=1
8 F: count_CHE>0 => count_CHE=0, ans=2
9 F: no effect (since count_CHE=0)
10 F: no effect
11 F: no effect
=> ans=2 matches.
Second example: "CHHHEEEFFCC"
Iterate:
1 C: count_C=1
2 H: count_C>0 => count_C=0, count_CH=1
3 H: count_C=0? Actually, see H: count_C=0, so condition fails; nothing happens? But we could use this H to start a new pattern? But we need C first. So we cannot use it. So count_CH remains 1? Actually algorithm: on H, if count_C>0 then convert one. Since count_C=0, we do nothing. So we lose this H. Should we consider using this H as part of a later pattern after a C? But if we skip it, maybe we could have used it for a different pattern? However, we already have one CH in progress. Could we have formed two patterns? Let's analyze string: positions: C(1), H(2), H(3), H(4? Actually given "CHHHEEEFFCC" length? Let's write: C H H H E E E F F C C. Count: C:3? Actually there are two C's at end? "CHHHEEEFFCC" : C H H H E E E F F C C. So Cs: pos1, pos10, pos11; Hs: pos2,3,4; Es: pos5,6,7; Fs: pos8,9. To form "CHEF", we need a C before H before E before F. Could we get 2? We have Cs: pos1,10,11; but after pos1 we have H, E, F. For second pattern, we need a C before some later H, E, F. But after pos10 or 11, there are no H, E, F (since end). So only one pattern can be formed: use C at pos1, H at pos2 or 3 or 4, E at pos5-7, F at pos8-9. So maximum should be 1. But algorithm gave? Let's simulate fully:
After pos1: count_C=1
pos2 H: count_C>0 => count_C=0, count_CH=1
pos3 H: count_C=0 so nothing; count_CH stays 1? Could we convert some CH to CHE? No, need E. So nothing.
pos4 H: same, nothing.
pos5 E: if count_CH>0 => count_CH=0, count_CHE=1
pos6 E: count_CHE=1? Actually after pos5, count_CH=0, count_CHE=1. On E, we check if count_CH>0? It's 0, so nothing. But perhaps we could have used later E for something else? Not needed.
pos7 E: similarly nothing.
pos8 F: if count_CHE>0 => count_CHE=0, ans=1
pos9 F: nothing.
pos10 C: count_C=1
pos11 C: count_C=2
End: ans=1. So matches.
Now, is this algorithm always optimal? I think yes for a pattern where characters are distinct? But pattern "CHEF" has distinct characters: C, H, E, F are all distinct. That simplifies. For distinct characters, the greedy algorithm above is optimal because we can treat it as a series of matches: each character can only be used once and must follow order. The algorithm essentially always uses the earliest possible C for the earliest possible H, etc., which doesn't waste resources. It's akin to computing the maximum number of increasing subsequences of a specific pattern? More formally, it's like computing the size of a maximum matching in a bipartite graph between positions of C, H, E, F with constraints i1 < i2 < i3 < i4. Since characters are distinct, the greedy algorithm that matches C to the earliest H, then earliest E, then earliest F, yields maximum number of quadruples? But careful: It's a chain: we need to match Cs to Hs, Hs to Es, Es to Fs. If we greedily match as we scan, we might not be optimal if we match a C to a H that could have been better used with a later E and F? But because the pattern is monotonic and distinct, the greedy for this type of matching is standard: For pattern "AB" with distinct characters, the greedy of using earliest possible B when scanning gives maximum pairs. For longer pattern, we can treat it as successive "AB" problems. However, there might be interdependencies: if we match a C to a H, we then need an E after that H. If we match a C to an early H, maybe that H could also serve as the start of another pattern? But H is only needed after a C, so it's not independent. The algorithm we described basically maintains counts of partial sequences: number of incomplete patterns that have seen a C (but not H), number that have seen CH, number that have seen CHE. When we encounter a character, we always try to extend the most advanced partial sequences that need that character. This is reminiscent of the "greedy for maximum number of non-overlapping subsequences" algorithm. I'm pretty sure it's correct for distinct letters, and I've seen this solution for many problems like "maximum number of "ABC" subsequences" etc.
But we should test some edge cases to ensure no counterexample.
Consider pattern "C", trivial? But pattern is length 4.
Consider S = "C H E F C H E F". That's two patterns interleaved? Actually "CHEFCHEF". Our algorithm:
- C: count_C=1
- H: count_C->count_CH=1, count_C=0
- E: count_CH->count_CHE=1, count_CH=0
- F: count_CHE->ans=1, count_CHE=0
- C: count_C=1
- H: count_C->count_CH=1
- E: count_CH->count_CHE=1
- F: count_CHE->ans=2
=> 2, optimal.
Consider S = "C C H H E E F F". Can we get 2? Yes. Algorithm:
- C: count_C=1
- C: count_C=2
- H: count_C>0 -> count_C=1, count_CH=1
- H: count_C>0 -> count_C=0, count_CH=2
- E: count_CH>0 -> count_CH=1, count_CHE=1
- E: count_CH>0 -> count_CH=0, count_CHE=2
- F: count_CHE>0 -> count_CHE=1, ans=1
- F: count_CHE>0 -> count_CHE=0, ans=2
=> 2.
Consider S = "C H H E E F". Can we get 1? Yes. Already did.
Consider S = "C H E F C H F E". Can we get 2? Let's analyze: S: C(1), H(2), E(3), F(4), C(5), H(6), F(7), E(8). We have two Cs, two Hs, two Es, two Fs. But ordering: After second C at pos5, we have H at 6, then F at 7, then E at 8. To get second pattern, we need H before E before F? Actually pattern CHEF: after C we need H, then E, then F. So for second pattern: C(5) -> need H after: pos6 is H good. Then need E after pos6: we have E at pos8. Then need F after pos8: there is no F after 8, so fails. Alternatively, could we use C(1) with H(2), E(3), F(4) for first pattern; then C(5) with H(6), but then need E after H(6) and then F after that E. We have E at pos8, but F at pos7 is before that E, so not valid. So only one pattern. But maybe we could use different assignment: C(1) with H(2), E(3), F(7)? But F(7) is after E(3) yes, but we need F after E. That's possible: C(1) -> H(2) -> E(3) -> F(7) yields pattern 1. Then remaining: C(5) -> H(6) -> need E after 6: we have E(8) -> then need F after 8: none. So still one. What about using C(5) with H(2)? Not allowed because H must be after C: H(2) is before C(5). So only one. So max=1. Algorithm:
- C: count_C=1
- H: count_C-> count_CH=1, count_C=0
- E: count_CH-> count_CHE=1, count_CH=0
- F: count_CHE-> ans=1, count_CHE=0
- C: count_C=1
- H: count_C-> count_CH=1
- F: (c=F) check: if count_CHE>0? 0, so no effect. (But we might think we could use this F to complete a pattern if we had a CHE waiting, but we don't.)
- E: (c=E) check if count_CH>0? Yes, count_CH=1 -> count_CH=0, count_CHE=1
End: ans=1. So correct.
Consider S = "C H E C H F E F". Can we get 2? Let's parse: positions: 1:C,2:H,3:E,4:C,5:H,6:F,7:E,8:F. First pattern: could use C1 H2 E3 F6 => first pattern. Then C4 H5 E7 F8 => second pattern? Check order: C4->H5 (good), H5->E7 (good), E7->F8 (good) => yes second pattern. So max=2. Algorithm:
- C1: count_C=1
- H2: count_C-> count_CH=1, count_C=0
- E3: count_CH-> count_CHE=1, count_CH=0
- C4: count_C=1 (since we see C, we increment count_C)
- H5: now we have count_C=1, so we convert to count_CH: count_C=0, count_CH=1 (note we already had count_CHE=1 from earlier)
- F6: check if count_CHE>0? Yes, we have count_CHE=1, so we complete one pattern: ans=1, count_CHE=0.
- E7: check if count_CH>0? Yes, count_CH=1, so convert to count_CHE=1.
- F8: check if count_CHE>0? Yes, so ans=2.
=> correct.
Consider S = "C H H E E E F F F". Can we get 2? Let's see: Cs:1, Hs:2, Es:3, Fs:3. We need ordering: C before H before E before F. We have one C only, so max is 1. So algorithm gives 1.
Now consider distinct characters but multiple Cs. The algorithm seems to work.
But is there any scenario where it's better not to extend a partial match immediately, but to reserve a character for a later, more beneficial match? For distinct characters, since each character appears only in one position in the pattern, the greedy of always using it to extend the longest possible partial match (i.e., always converting when possible) is optimal. This can be proven via exchange argument: if we have an optimal set of matches, we can reorder them to follow the greedy order without reducing count.
Alternatively, we can think of this as a flow problem with four layers: positions of C, H, E, F. We need to select as many disjoint directed paths from a C to an H to an E to an F with increasing indices. This is a maximum cardinality matching in a DAG. Since the graph is a chain of bipartite matchings, the greedy algorithm that processes nodes in order and matches whenever possible yields maximum matching. Actually, it's analogous to computing the size of a maximum set of vertex-disjoint increasing sequences in a 3-partite graph. There is a known concept of "online matching" where greedy works for intervals? Not exactly.
But we can also solve via DP using counts: we can compute the maximum number of complete patterns as min( some computed values). However, given constraints up to 100k, the greedy O(n) algorithm is fine.
Thus, the solution: scan S, maintain cntC, cntCH, cntCHE (counts of patterns that have matched up to that prefix). For each character c:
- if c == 'C': cntC++
- else if c == 'H': if cntC > 0: cntC--, cntCH++
- else if c == 'E': if cntCH > 0: cntCH--, cntCHE++
- else if c == 'F': if cntCHE > 0: cntCHE--, ans++
Finally output ans.
We need to verify that this algorithm indeed maximizes the number of moves. Let's attempt to prove or find counterexample.
Suppose pattern "AB" with distinct letters. The algorithm: cntA=0, ans=0. For each char: if 'A', cntA++; if 'B' and cntA>0: cntA--, ans++. This is known to yield maximum number of disjoint "AB" subsequences. Because any 'B' can only pair with a preceding 'A', and using the earliest available 'A' is optimal.
Now for "ABC", we can think similarly: maintain cntA, cntAB, ans. For each char: if 'A', cntA++; if 'B' and cntA>0: cntA--, cntAB++; if 'C' and cntAB>0: cntAB--, ans++. Is this optimal? This can be seen as a pipeline: we want to maximize number of completed ABCs. The pipeline's capacity is limited by the minimal of something. It's like we have three stages; each character either enters stage 1 (A), moves from stage1 to stage2 (B), or from stage2 to stage3 (C). The greedy rule of moving as soon as possible maximizes throughput because there is no advantage to delaying: if we have an A and later see a B, using that B to convert an A to AB is always beneficial because it brings us closer to completion, and leaving the A unused may result in later lacking B to pair, but using B now doesn't preclude using a later A? Actually, we might have a scenario: S = "A B B". For pattern "AB". Greedy: cntA=1 after first A, then B: pair, ans=1, cntA=0. Next B: no A, ans remains 1. Could there be a better? No, only one A so max=1.
Now consider "AB" with S = "A A B". Greedy: after first A cntA=1, second A cntA=2, then B: pair, ans=1, cntA=1. So ans=1, but could we get 1? Actually we have two As and one B, max pairs = 1 because only one B. So fine.
Now for "ABC", consider S = "A B A B C". Can we get 1 or 2? Let's see: we have two As, two Bs, one C. To get two ABC, we need two Cs, so max 1. Greedy:
- A: cntA=1
- B: cntA>0 => cntA=0, cntAB=1
- A: cntA=1
- B: now we have cntA=1, so B converts that A to AB: cntA=0, cntAB=2? Actually careful: after third char A, cntA=1. At fourth char B, we check: if cntA>0, yes, so cntA-- (0), cntAB++ (now cntAB=2).
- C: cntAB>0, so convert one AB to ans: cntAB=1, ans=1.
End: ans=1, leftover cntAB=1 (meaning one AB partial) but no C. So ans=1, correct.
What about S = "A A B B C C"? Expect 2. Greedy:
- A: cntA=1
- A: cntA=2
- B: cntA>0 => cntA=1, cntAB=1
- B: cntA>0 => cntA=0, cntAB=2
- C: cntAB>0 => cntAB=1, ans=1
- C: cntAB>0 => cntAB=0, ans=2
Works.
Now consider a tricky case for "ABC": S = "A B B C". Could we get 2? No, only one A, one C? Actually there is one A, two B, one C => max 1. Greedy: A->cntA=1; B->cntA->cntAB=1; B-> cntA=0? But after first B, cntA=0, cntAB=1. Next B: condition is for B: if cntA>0? It's 0, so no action. Some might think we could use second B to start a new AB? But need A before B. So cannot. Then C: cntAB>0 -> ans=1. So ok.
Now consider "ABAC" but pattern distinct? Not relevant.
So for distinct letters, greedy works.
But is it always optimal for any pattern? Actually there is known result: The greedy algorithm that processes characters and updates the longest possible partial match is optimal for maximizing number of disjoint occurrences of a given word, regardless of pattern (even with repeats) as long as we process characters from left to right and for each character, we try to extend the longest possible partial match (i.e., the one with the most characters matched so far). However, I recall some nuance: for pattern with repeated characters, you might need to update from the end to avoid double counting. For example, pattern "AAA": we want maximum number of disjoint subsequences "AAA". The greedy algorithm of maintaining counts for each prefix: on 'A', we could decide to extend from state2 (needs third A) first, then state1, then state0. If we do it in increasing order, it might not be optimal. For "AAA", we want to maximize number of triples. The optimal strategy is to treat it as a resource allocation: we have many As, we need groups of 3 in order. Since the As are all same, any three As in increasing positions can form a pattern. So the maximum number is floor(total A / 3). But if we do greedy like: countA=0, countAA=0, ans=0. For each 'A': if countAA>0 then complete a triple? Actually we need to decide order: upon seeing 'A', we should first try to complete a near-complete pattern (i.e., those waiting for third A), then extend those waiting for second A, then start a new one. So the algorithm: if c matches pattern[2] (third char), and count[2] (partial of length 2) >0, then ans++, decrement count[2]; else if matches pattern[1] and count[1]>0, then count[1]--, count[2]++; else if matches pattern[0], then count[0]++ (or count[1]++? careful). Actually for "AAA", we want to maximize triples. The optimal is to assign As to as many triples as possible. The greedy that always starts a new triple as soon as possible? Let's test: S = "A A A A". Greedy algorithm that updates in order of increasing prefix: on each A, we increment countA (state1). Then if we later see A, we could convert a state1 to state2, etc. If we do it naively:
- A1: cnt1=1
- A2: since cnt1>0, we could convert to cnt2: cnt1=0, cnt2=1
- A3: since cnt2>0, convert to ans: ans=1, cnt2=0
- A4: cnt1=1 (since no conversion possible)
At end, ans=1, but maximum is 1 (since 4 As gives floor(4/3)=1). So okay.
But what about S = "A A A A A A"? 6 As, max 2. Greedy as above:
- A1: cnt1=1
- A2: cnt1>0 => cnt1=0, cnt2=1
- A3: cnt2>0 => ans=1, cnt2=0
- A4: cnt1=1
- A5: cnt1>0 => cnt1=0, cnt2=1
- A6: cnt2>0 => ans=2, cnt2=0
=> ans=2. Good.
But what about pattern "ABA"? This has repeated 'A'. Could greedy be suboptimal? Let's test: pattern "ABA". We want maximum number of disjoint "ABA". S = "A B A B A". Can we get 2? Let's see: positions: 1:A,2:B,3:A,4:B,5:A. To form two "ABA": need two sequences each A, B, A in order. Possibility: first: A1, B2, A3. Second: A3? can't reuse. A1? used. Need distinct indices. Maybe: first: A1, B2, A5; second: A3, B4, ? need A after B4: A5 already used. Could use A3, B4, A5? That would be A3, B4, A5 gives pattern ABA? A3, B4, A5 => yes A, B, A. But then first uses A1, B2, A3? conflict with A3. So only one can be formed? Let's check systematically: we have three As and two Bs. To form ABA, need one B between two As, with order A before B before A. The number of such triples is limited by number of Bs and As. Since we need two As per B? Actually each triple uses one B and two As, with As on either side of B. Since we have 3 As and 2 Bs, we could theoretically get 1 triple because the As must be arranged: we need an A before a B and a different A after that B. With As at positions 1,3,5 and Bs at 2,4, we could possibly have two triples: Triple1: A1, B2, A3. Triple2: A3? but need an A after B4: A5 works, but then A3 would be used in both triples. Alternatively, Triple1: A1, B2, A5 (since A5 after B2), Triple2: A3, B4, ? need A after B4: A5 is after but used. So only one triple. So max=1. Greedy algorithm: maintain cntA (after first A), cntAB (after AB), ans. For pattern "ABA", we need to define states:
state0: want first A
state1: have A, want B
state2: have AB, want final A
When we see character:
- If 'A': we could start a new pattern (state0->state1) if we want; also we could complete a pattern if we are in state2 (waiting for A). Since 'A' can serve both as first A and as final A. To maximize, we should prioritize completing patterns (state2) over starting new ones, because completing yields a full pattern and frees resources? But starting new might later be completed. The greedy algorithm that always extends the longest possible partial match (i.e., if we have state2 waiting, use 'A' to complete; else if state1 waiting, use 'B' to advance; else if state0 waiting? Actually state0 is implicit infinite; we can always start a new pattern on 'A' if we don't use it for completion). For "ABA", the algorithm should be: on seeing 'A': if cntAB>0 (state2), then complete: ans++, cntAB--; else start new: cntA++. On seeing 'B': if cntA>0, then cntA--, cntAB++. Let's test on S = "A B A B A".
- A1: cntAB=0, so start: cntA=1
- B2: cntA>0 => cntA=0, cntAB=1
- A3: cntAB>0 => complete: ans=1, cntAB=0
- B4: cntA=0, so nothing
- A5: cntAB=0, start: cntA=1
End: ans=1, cntA=1 leftover. So ans=1, matches optimum.
Now, could there be a scenario where it's better not to complete a pattern but to start a new one? Consider S = "A A B A B A". Let's list: 1:A,2:A,3:B,4:A,5:B,6:A. Can we get 2 triples? We have As at 1,2,4,6 (4 As) and Bs at 3,5 (2 Bs). Need two triples. Possible assignments: Triple1: A1, B3, A4. Triple2: A2, B5, A6. That uses As 1,2,4,6 and Bs 3,5. All indices increasing: 1<3<4, 2<5<6, yes. So max=2. Let's see greedy:
- A1: cntAB=0 => cntA=1
- A2: cntAB=0? Still 0, so cntA=2 (since we have two starts)
- B3: cntA>0 => cntA=1, cntAB=1
- A4: cntAB>0 => complete one: ans=1, cntAB=0. Now after completion, cntAB=0.
- B5: cntA>0 (cntA=1) => cntA=0, cntAB=1
- A6: cntAB>0 => complete: ans=2, cntAB=0.
=> ans=2. Good.
Consider S = "A B A A B A". positions: 1:A,2:B,3:A,4:A,5:B,6:A. As:1,3,4,6; Bs:2,5. Can we get 2? Triple1: A1,B2,A3. Triple2: A4,B5,A6? Check order: 4<5<6 works, but A4 is after A3. That uses As 1,3,4,6; all distinct. Yes 2. Greedy:
- A1: cntA=1
- B2: cntA>0 => cntA=0, cntAB=1
- A3: cntAB>0 => complete ans=1, cntAB=0
- A4: cntAB=0 => cntA=1
- B5: cntA>0 => cntA=0, cntAB=1
- A6: cntAB>0 => ans=2.
=> 2.
Consider S = "A B B A A B A". Let's see if greedy fails? 1:A,2:B,3:B,4:A,5:A,6:B,7:A. As:1,4,5,7; Bs:2,3,6. Can we get 2 triples? Need two Bs. Let's attempt: Triple1: A1,B2,A4. Triple2: A4? conflict; maybe A1,B2,A5? 1<2<5 ok. Then second triple: need A before B and A after. Could use A4,B6,A7? 4<6<7 ok, but A4 used? In first triple used A1, B2, A5. So A4 free, B6, A7 free. That works: A4,B6,A7. So two triples using As 1,5,4,7? Wait, triple1 uses A1 and A5; triple2 uses A4 and A7. All distinct. So 2 triples. Greedy:
- A1: cntA=1
- B2: cntA>0 => cntA=0, cntAB=1
- B3: cntA=0, so nothing? (since we only convert if cntA>0; but we have cntAB>0? but B doesn't affect cntAB; it only can convert cntA to cntAB. So B3 does nothing.)
- A4: cntAB>0 => complete ans=1, cntAB=0
- A5: cntAB=0 => cntA=1
- B6: cntA>0 => cntA=0, cntAB=1
- A7: cntAB>0 => ans=2, cntAB=0.
=> ans=2. Good.
Now consider scenario where we might want to not complete a pattern with an A that could also be used as first A for a later pattern that would yield an extra pattern overall. For "ABA", imagine S = "A B A A B A". We already did that and greedy gave 2. What about "A A B A B A"? Greedy gave 2. So seems fine.
But what about pattern "ABCA"? with repeated 'A'? Might need careful order of updates.
Nevertheless, for "CHEF", all letters are distinct, so the simple greedy (always convert when possible) should be optimal. Moreover, the algorithm as described (C -> H -> E -> F) with the conditions exactly as described is correct.
But wait: In our algorithm for distinct letters, we do for each character:
- if 'C': cntC++
- if 'H': if cntC > 0: cntC--, cntCH++
- if 'E': if cntCH > 0: cntCH--, cntCHE++
- if 'F': if cntCHE > 0: cntCHE--, ans++
This is essentially the greedy that when we see an 'H', we pair it with the earliest available 'C' (since we decrement cntC, which represents count of unmatched 'C's encountered so far). This seems to be using first-come-first-served for pairing, which should be optimal.
We could also think of it as: The maximum number of moves is the minimum over all prefixes of something? Actually it's like: Let f1 = total number of 'C's; but ordering matters. But the algorithm accounts for ordering.
We should also consider if there is any scenario where we might want to skip a 'C' to use a later 'C' to allow more 'H's? For example, suppose we have many 'H's early and few 'C's later. If we pair an early 'C' with an early 'H', we might waste that 'C' that could have been used with a later 'H' that otherwise would have no 'C' before it? But since 'H's need a preceding 'C', if we have a later 'H', it can be paired with any earlier 'C' (including the one we used earlier). But if we pair the earliest 'C' with the earliest 'H', we still have other Cs? Actually, consider: S = "C H H". Only one C, two Hs. Greedy: C->cntC=1; H1: pair -> cntC=0, cntCH=1; H2: cntC=0, so nothing. So we get one CH partial. Could we have gotten two CH? No, because need two Cs. So fine.
Consider "C C H H" we already did: greedy yields cntCH=2, which is optimal.
What about ordering like "H C H C"? Actually first character H, then C. Since pattern starts with C, the initial H cannot be used without preceding C. So it's wasted. Greedy: H: nothing; C: cntC=1; H: cntC>0 -> cntC=0, cntCH=1; C: cntC=1. So we have one CH partial and one leftover C. Could we have done better? Only one H after a C? Actually we have two H's: first H at pos1 cannot be used; second H at pos3 used with C at pos2; leftover C at pos4. So only one possible CH. That's max.
Thus, algorithm stands.
Now, constraints up to 100k, O(n) is fine.
Thus, answer is straightforward.
But wait: The problem statement says: "Chef takes a subsequence of string's letters that form the word "CHEF" and then he removes that symbols." The goal is maximal number of moves. So each move removes exactly 4 letters (the ones in the subsequence). The process repeats. This is exactly the maximum number of disjoint "CHEF" subsequences.
Our greedy algorithm returns that number. But we need to be careful: Is it allowed to pick any subsequence each time, and we remove them, then continue? This is equivalent to selecting a set of disjoint subsequences (they can't share characters). Yes.
Now, is it always optimal to take the subsequences greedily in the order described by the scanning algorithm? Could there be a scenario where you could get more moves by not taking a "CHEF" that is available early to preserve letters for later moves? Since letters are removed only after picking a subsequence, the order of picking might affect possibilities. However, the maximum number of disjoint subsequences is independent of the order of removal; it's a combinatorial maximum. So we can compute the maximum size of a set of indices that can be partitioned into increasing "CHEF" patterns.
Therefore, our algorithm is correct.
Double-check with some random strings using brute force for small lengths to ensure correctness. Since we are ChatGPT, we can't run code, but we can reason.
Let's test all possible small strings manually? Not needed.
I think it's fine.
Thus solution: read string, run the four counters, print ans.
But we must be careful about integer overflow? Counts can be up to length, which is 100k, so int is fine.
Edge cases: empty? |S| >=1. All characters are from {C, H, E, F}. So no other letters.
Therefore, answer is trivial.
However, I'm seeing the problem might be from CodeChef (CHEF in string). I recall a problem "CHEF in string" where the answer is the number of subsequences "CHEF" but not necessarily disjoint? Actually maybe the game is to remove subsequence "CHEF" repeatedly, maximizing moves. The solution I recall is indeed the greedy algorithm described. So I'm confident.
Thus final answer.
But wait, the problem statement: "Chef takes a subsequence of string's letters that form the word "CHEF" and then he removes that symbols." Could it be that after each removal, the string concatenates (so the relative order of remaining letters is preserved). That's the same as selecting disjoint subsequences from the original string (since removal doesn't change order of remaining letters, and subsequent moves pick subsequence from the remaining string). Yes.
Thus the solution.
We'll produce a solution in C++ (or Python as requested? The user didn't specify language, but we need to output code? The problem likely expects code. However, the user only asks: "Please, help Chef and tell him the maximal possible number of moves that he is able to make for the given string S." It's a typical programming problem. In this environment, we usually provide the solution explanation and possibly code. But the instruction says: "You are an AI assistant that solves competitive programming problems. Provide the final answer in the format: a single line containing the maximal possible number of moves." Actually, the user might be expecting just the answer for the given test case? No, the problem is to write a program that reads input and outputs answer. The user provided two examples, but typically they'd want a solution. However, the prompt says: "Input: The first line of each test case contains a given string." It looks like they are describing a problem and want code. But the conversation: "Chef likes playing with strings..." It's a problem statement. Then "Please, help Chef..." Possibly they want us to output the answer for the provided input? But they gave two examples, not a specific input. Actually they wrote "Input: CHEFCHEFFFF Output: 2 Input: CHHHEEEFFCC Output: 1". That's just example. So they want a general solution.
The final answer should be a code snippet? The instruction says: "You are an AI assistant that solves competitive programming problems. Provide the final answer in the format: a single line containing the maximal possible number of moves." That suggests that for a given input, we output the answer. But the problem statement is typical of an interactive problem? Hmm.
Given the context, I think the user expects us to provide a solution (algorithm) and maybe code. However, as per the instructions, we need to output just the maximal number? Possibly the user will provide a specific string as input, and we need to output the answer. But the conversation did not include a specific test case; it included examples. So maybe they want us to write a program that reads from stdin and writes to stdout. In typical ChatGPT interactions, we provide the code.
Given that this is a competition programming problem, I will provide a C++ solution.
But the instruction "Provide the final answer in the format: a single line containing the maximal possible number of moves." might be ambiguous. It could mean that we need to output the answer for the given input, but no input is provided in the query. Actually the query does not contain a specific test case; it just states the problem. The user might be asking us to solve the problem (i.e., write a program). In many such scenarios, we produce the solution code.
Thus, I'll answer with an explanation and then provide code in C++.
To be safe, I'll write a concise solution explanation and the code.
Also, we should note that there could be multiple test cases? The problem statement says "The first line of each test case contains a given string." It might imply multiple test cases, but no T is given. Usually CodeChef problems specify number of test cases. Here it says "The first line of each test case contains a given string." That might indicate there can be multiple test cases, but it's ambiguous. Possibly it's a single test case. I've seen a problem "CHEF in string" from CodeChef: it has a single string input. So I'll assume one test case.
Thus, code:
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
cin >> s;
int cntC = 0, cntCH = 0, cntCHE = 0, ans = 0;
for (char c : s) {
if (c == 'C') {
cntC++;
} else if (c == 'H') {
if (cntC > 0) {
cntC--;
cntCH++;
}
} else if (c == 'E') {
if (cntCH > 0) {
cntCH--;
cntCHE++;
}
} else if (c == 'F') {
if (cntCHE > 0) {
cntCHE--;
ans++;
}
}
}
cout << ans << endl;
return 0;
}
That's it.
But we should also consider that there might be leading/trailing spaces or newline. Using cin >> s reads a word (no spaces). Since string consists only of uppercase letters, it's fine.
Time complexity O(|S|), memory O(1).
Now, verify with examples:
Input: CHEFCHEFFFF -> output 2.
Input: CHHHEEEFFCC -> output 1.
Works.
Thus final answer: provide code.
Given the instruction "Provide the final answer in the format: a single line containing the maximal possible number of moves.", they might want just the number for a specific hidden test. But I think providing code is appropriate.
I'll output the code. ```cpp
#include
#include
using namespace std;
int main() {
string s;
cin >> s;
int cntC = 0, cntCH = 0, cntCHE = 0, ans = 0;
for (char c : s) {
if (c == 'C') {
cntC++;
} else if (c == 'H') {
if (cntC > 0) {
cntC--;
cntCH++;
}
} else if (c == 'E') {
if (cntCH > 0) {
cntCH--;
cntCHE++;
}
} else if (c == 'F') {
if (cntCHE > 0) {
cntCHE--;
ans++;
}
}
}
cout << ans << endl;
return 0;
}