STRING KA KHEL

Posted: 11 Mar, 2021
Difficulty: Moderate

PROBLEM STATEMENT

Try Problem

Ninja started a gaming shop and for that shop, he is planning to make a new game ‘String Ka Khel’. In that game user is provided with ‘N’ number of strings and he has to find out the maximum length of strings he can form by joining these ‘N’ strings. For joining two strings there is a condition that two strings will only join if the last character of the first string is same as the last character of the second string. If the user will find out the correct answer he will be given Coding Ninja goodies by the Ninja.

So your task is to find the maximum length of string which can be formed by joining strings according to the given condition. If no such combination exists return ‘0’. Strings only contain the letter ‘B’ and ‘R’.

Example:

The string is ‘RR’, ‘RB’ so we can combine ‘RR’ and ‘RB’ as the last character of ‘RR’ i.e ‘R’ matches with the first character of ‘RB’. But we cant combine ‘RB’ and ‘RR’ as the last character of ‘RB’ i.e ‘B’ doesn't matches with the first character of ‘RR’ i.e ‘R’ so our answer is '4'.

Input Format:

The first line of input contains an integer ‘T’ denoting the number of test cases.

The first line of each test case contains an integer ‘N’ denoting the number of strings.

The second line of each test case contains ‘N’ space-separated strings.

Output Format:

For each test case, print a single line containing a single integer denoting the maximum length of string which can be formed. In case no two strings can add simply print ‘0’.

The output of each test case will be printed in a separate line.
Note:
You do not need to print anything. It has already been taken care of. Just implement the given function.

Constraints:

1 <= T <= 100
2 <= N <= 1000
1 <= | ST | <= 1000    

Where ‘T’ represents the number of test cases and ‘N’ represents the total number of strings and '|ST|' represents the length of each of the ‘N’ strings.

Time Limit: 1 second    
Approach 1
  • We have to find out all the possible permutations by satisfying the given condition. For this, we make another helper function that also takes into count the index. So starting from the first index of our vector we have to go to the last index.
  • So for checking all the permutations, we run a loop that swaps the element of the vector array so we get all the possible permutations and for every permutation, we check how many maximum elements are satisfying our required condition that the last character of the first element is equal to the last character of the second element.
  • So for checking with every index we call a recursive function and store the max so that we are able to get our maximum value after every recursive function.
  • Hence at last we simply return our maximum count as an answer.
Try Problem