FastPrepGet Optimal String Length

Get Optimal String Length

IBM logoIBM● MediumFULLTIMEOA

Problem 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:

  • 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

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 = 7

The 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 = 5

The maximal length optimal string is 'ABABA'.

Constraints

  • 0 ≤ countA, countB, maxA, maxB ≤ 106

More IBM problems

See IBM hiring insights
Saved
public long getOptimalStringLength(int countA, int countB, int maxA, int maxB) {
  // write your code here
}
countA3
countB5
maxA1
maxB1
expected7
Checking account…