Problem · Math
Get Optimal String Length
Learn this problemProblem statement
A string is to be constructed using only the characters 'A' and 'B'. Given four integers,
countA, countB, maxA, maxB, the constructed
string is said to be optimal if:
countA 'A' characters, and countB 'B' characters.maxA 'A' characters.maxB 'B' characters.HackerRank organized fun trivia for its employees where it asked for the maximum possible length of an optimal string that can be constructed satisfying the criteria above. The goal is to find the maximum possible length of an optimal string.
Note:
- There can be multiple optimal strings with the same maximal length.
- A substring of a string is a contiguous subsegment of the string.
Function
getOptimalStringLength(countA: int, countB: int, maxA: int, maxB: int) → long
Complete the function getOptimalStringLength in the editor.
getOptimalStringLength has the following parameters:
int countA: the maximum count of character 'A'int countB: the maximum count of character 'B'int maxA: the maximum substring length of character 'A'int maxB: the maximum substring length of character 'B'
Returns
long integer: the maximum length of optimal string that can be constructed
Examples
Example 1
countA = 3countB = 5maxA = 1maxB = 1return = 7The maximal length optimal string that can be constructed is 'BABABAB' whose length is 7. Thus, the answer is 7.
Example 2
countA = 2countB = 4maxA = 2maxB = 1return = 5The maximal length optimal string is 'ABABA'.
Constraints
0 ≤ countA, countB, maxA, maxB ≤ 106More IBM problems
- Parent Process NumberOA · Seen Jul 2026
- Request Retry CountOA · Seen Jul 2026
- Count Strictly Increasing Subsequences of Length 3OA · Seen Jul 2026
- Maximum Requests in a Time WindowOA · Seen Jul 2026
- Query Type Frequency WindowOA · Seen Jul 2026
- Minimum Number of Non-Empty Disjoint SegmentsOA · Seen Jul 2026
- Spam Text ClassificationOA · Seen Jul 2026
- Count Ideal NumbersOA · Seen Jun 2026