<p>You are given three integers <code>x</code>, <code>y</code>, and <code>z</code>.</p>

<p>You have <code>x</code> strings equal to <code>&quot;AA&quot;</code>, <code>y</code> strings equal to <code>&quot;BB&quot;</code>, and <code>z</code> strings equal to <code>&quot;AB&quot;</code>. 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 <code>&quot;AAA&quot;</code> or <code>&quot;BBB&quot;</code> as a substring.</p>

<p>Return <em>the maximum possible length of the new string</em>.</p>

<p>A <b>substring</b> is a contiguous <strong>non-empty</strong> sequence of characters within a string.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

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

<p><strong class="example">Example 2:</strong></p>

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

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= x, y, z &lt;= 50</code></li>
</ul>

class Solution:
    def longestString(self, x: int, y: int, z: int) -> int:
        # Given that we already have a valid string, and we would like to append more units onto it. Note that the constraint works for the suffix of the current string, which has only 3 cases:
        # 1. AA: We should only append BB.
        # 2. BB: We can append AA or AB.
        # 3. AB: We can append AA or AB.
        # We have M1(x, y, z) = M2(x, y - 1, z)
        # M2(x, y, z) = max(M1(x - 1, y, z), M3(x, y, z - 1))
        # M3(x, y, z) = max(M1(x - 1, y, z), M3(x, y, z - 1))
        # Approach 2: Greedy approach
        # y can be consumed only with prior x. Hence we should consume y in priority.
        # 1. if x > y, we form AABB..AA, then append all AB's at the front of the string.
        # 2. if x < y, we form BBAA..BB, then append all AB's at the end of the string.
        # 3. If x == y, we form AABB..AABB then append all AB's at the end of the string
        return ((x + y) * 2 if x == y else (2 * min(x, y) + 1) * 2) + z * 2
47