
Input: ‘N’ = 4, ‘S’ = “XYYX”
Output: 4.
Select ‘i’ = 1 and ‘j’ = 2. Flip all the characters of the substring from 1 to 2, and we get ‘S’ = ‘XXXX’. Hence, the number of ‘X’s is 4.
The first line will contain the integer 'T', denoting the number of test cases.
The first line of each test case contains an integer ‘N’ denoting the length of the string ‘S’.
The second line of each test case contains an arbitrary string ‘S’.
For each test case, you don’t need to print anything just return the maximum number ‘X’s you can get after performing exactly one operation.
You don't need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^6
Sum of N Over all the Test cases <= 10^6
Time Limit: 1 sec
In this approach, We need to find a substring that when flipped contributes a maximum number of ‘X’ to the whole string. We can run two nested for loops to get all possible substrings then for each substring we can calculate how many ‘X’ that substring will contribute when it will be flipped.
In this approach, the idea is to substitute the value of ‘X’ with -1 and the value of ‘Y’ with 1. Now this problem is transformed into well known problem “Finding subarray with mamxium sum”. To get the subarray with maximum sum we can iterate over all the elements and add its value to the variable ‘SUM’ and then update the maximum sum. If ‘SUM’ < 0 then we update the value of ‘SUM’ to 0.
We can find the starting and ending index of the subarray with maximum sum by modifying the Kadane Algorithm a little bit. Then we run a loop from 0 to the starting index -1 of the subarray and then count the number of ‘X’, then we iterate over the subarray from starting index to the ending index and count the number of ‘Y’ (since it will be flipped to ‘X’) and finally we iterate from ending index + 1 to the last character of the string and count the number of ‘X’. The final answer will be the sum of all the counts.