Construct the Longest New String Problem
Description
LeetCode Problem 2745.
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 concatenate 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 concatenate 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 concatenate 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:
1 <= x, y, z <= 50
Solution
Approach: Case analysis
A piece "AA" can only be followed by "BB" (else AAA appears) and "BB" can only be followed by "AA", so these two alternate. The "AB" pieces can all go once at the front of an "AA" or after a "BB", so they never get in the way. The shorter of the two counts limits the alternating chain:
- If
x < y:BB AA BB AA ... BBusesxAAs andx + 1BBs, then add thezABs: length(2x + z + 1) * 2. - If
x > y: symmetric, length(2y + z + 1) * 2. - If
x == y:AA BB AA BB ...uses all of them, plus the ABs: length(x + y + z) * 2.
Complexity: O(1) time and space.
class Solution:
def longestString(self, x: int, y: int, z: int) -> int:
if x < y:
return (x * 2 + z + 1) * 2
if x > y:
return (y * 2 + z + 1) * 2
return (x + y + z) * 2