Description
Solutions
Submission
Get Optimal String Length
🔥 FULLTIME

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:

  • There are at most countA 'A' characters, and countB 'B' characters.
  • Each substring of only 'A's contains at most maxA 'A' characters.
  • Each substring of only 'B's contains at most 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 Description

    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

    Example 1:

    Input:  countA = 3, countB = 5, maxA = 1, maxB = 1
    Output: 7
    Explanation:
    The maximal length optimal string that can be constructed is 'BABABAB' whose length is 7. Thus, the answer is 7.

    Example 2:

    Input:  countA = 2, countB = 4, maxA = 2, maxB = 1
    Output: 5
    Explanation:
    The maximal length optimal string is 'ABABA'.
    Constraints:
      0 ≤ countA, countB, maxA, maxB ≤ 106
    Thumbnail 0
    Testcase

    Result
    Case 1

    input:

    output: