2745. Construct the Longest New String

Difficulty:
Related Topics:
Similar Questions:

    Problem

    You are given three integers x, y, and z.

    You have x strings equal to "AA", y strings equal to "BB", and z strings equal to "AB". You want to choose some (possibly all or none) of these strings and concactenate them in some order to form a new string. This new string must not contain "AAA" or "BBB" as a substring.

    Return the maximum possible length of the new string.

    A substring is a contiguous non-empty sequence of characters within a string.

    Example 1:

    Input: x = 2, y = 5, z = 1
    Output: 12
    Explanation: We can concactenate the strings "BB", "AA", "BB", "AA", "BB", and "AB" in that order. Then, our new string is "BBAABBAABBAB".
    That string has length 12, and we can show that it is impossible to construct a string of longer length.
    

    Example 2:

    Input: x = 3, y = 2, z = 2
    Output: 14
    Explanation: We can concactenate the strings "AB", "AB", "AA", "BB", "AA", "BB", and "AA" in that order. Then, our new string is "ABABAABBAABBAA".
    That string has length 14, and we can show that it is impossible to construct a string of longer length.
    

    Constraints:

    Solution (Java)

    class Solution {
        public int longestString(int x, int y, int z) {
            int longestString = 0;
    
            //Account for 'AB' repetitions
            //AB is versatile because they can be used back to back or they can be used prepended by BB or appended by AA
            //Because AA, BB are best used together, then we should just stick to alternating AB-AB together
            longestString += z * 2;
    
            //Start alternating AABB pairs
            //AA and BB are best used when used together first since they are worth 4 together
            int aabbCount =  Math.min(x, y);
    
            longestString += aabbCount * 4;
            x -= aabbCount;
            y -= aabbCount;
    
            //Account for leftover AA,BB
    
            //Lastly, append an AA if possible
            if(x > 0) {
                longestString +=2;
            }
    
            //Lastly, prepend BB if possible
            if(y > 0) {
                longestString +=2;
            }
    
            //End product looks like {Singular BB prepend if available} + {ABAB... pairs} + {AABB... pairs}  + {Singular AA append if available}
            //ex: BB-ABABABABABAB-AABBAABB-AA
    
            return longestString;
    
        }
    }
    

    Explain:

    nope.

    Complexity: