FastPrepFastPrep
Problem Brief

Get Optimal String Length

FULLTIMEOA
See IBM online assessment and hiring insights

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

    1Example 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.

    2Example 2

    Input
    countA = 2, countB = 4, maxA = 2, maxB = 1
    Output
    5
    Explanation
    The maximal length optimal string is 'ABABA'.

    Constraints

    Limits and guarantees your solution can rely on.

    0 ≤ countA, countB, maxA, maxB ≤ 106
    public long getOptimalStringLength(int countA, int countB, int maxA, int maxB) {
      // write your code here
    }
    
    Input

    countA

    3

    countB

    5

    maxA

    1

    maxB

    1

    Output

    7

    Sign in to submit your solution.