Problem · String

Minimum Value Calculation by Replacing '!' in a Binary String

Learn this problem
MediumAmazonFULLTIMEOA
See Amazon hiring insights

Problem statement

You are given a string consisting of '0', '1', and '!', where '!' represents a character that can be replaced with either '0' or '1'. Additionally, you are given two integers x and y.

Your task is to replace all '!' characters in such a way that you minimize the calculated value based on the following rules:

  • For every adjacent pair of characters:
  • If the pair is '01', the contribution to the total is x.
  • If the pair is '10', the contribution to the total is y.
  • Function

    calculateMinimumValue(s: String, x: int, y: int) → int

    Complete the function calculateMinimumValue in the editor.

    calculateMinimumValue has the following parameters:

    1. 1. String s: a binary string containing '0', '1', and '!' characters
    2. 2. int x: the contribution value for '01' pairs
    3. 3. int y: the contribution value for '10' pairs

    Returns

    int: the minimum calculated value after replacing all '!' characters

    Examples

    Example 1

    s = "01!0"x = 2y = 3return = 8
    Replace '!' with '0' to get '0100': Pairs: ('01', '10') → Contribution: ( 2 imes 1 + 2 imes 3 = 8 ) Replace '!' with '1' to get '0110': Pairs: ('01', '10') → Contribution: ( 2 imes 2 + 2 imes 3 = 10 ) The minimum contribution is ( 8 ).

    Example 2

    s = "!0!1"x = 3y = 4return = 7
    Replace the first '!' with '1' and the second '!' with '0' to get '10' and '01': Pairs: ('10', '01') → Contribution: ( 3 + 4 = 7 )

    Constraints

  • The string contains at least one '!', and its length is between 1 and ( 10^5 )
  • ( x ) and ( y ) are non-negative integers
  • More Amazon problems

    drafts saved locally
    public int calculateMinimumValue(String s, int x, int y) {
      // write your code here
    }
    
    s"01!0"
    x2
    y3
    expected8
    checking account