Construct the Longest New String - 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 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.
Input & Output
Example 1 — Balanced Case
$
Input:
x = 1, y = 1, z = 1
›
Output:
6
💡 Note:
We have 1 "AA", 1 "BB", 1 "AB". Total A's = 2+1 = 3, Total B's = 2+1 = 3. Since they're equal, we can use all characters: length = 6. One valid arrangement: "AABBAB"
Example 2 — Imbalanced Case
$
Input:
x = 2, y = 1, z = 1
›
Output:
7
💡 Note:
We have 2 "AA", 1 "BB", 1 "AB". Total A's = 4+1 = 5, Total B's = 2+1 = 3. Since |5-3| = 2 > 1, we use formula: 2×min(5,3)+1 = 7. One valid arrangement: "AABABAA"
Example 3 — No AB Strings
$
Input:
x = 0, y = 1, z = 0
›
Output:
2
💡 Note:
We only have 1 "BB" string. Total A's = 0, Total B's = 2. We can use the entire "BB" string since it doesn't create "BBB". Length = 2.
Constraints
- 1 ≤ x, y, z ≤ 50
Visualization
Tap to expand
Understanding the Visualization
1
Input
Given counts of AA, BB, and AB strings
2
Analysis
Count total A's and B's, check balance
3
Construction
Build longest string without AAA/BBB
Key Takeaway
🎯 Key Insight: The maximum length depends on balancing A and B characters optimally - AB strings help bridge the gap between imbalanced counts
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code