Problem · String

Maximum Number Possible

Learn this problem
EasyMicrosoft logoMicrosoftFULLTIMEOA
See Microsoft hiring insights

Problem statement

You are given a string s representing a positive integer and an integer k. In one operation, choose a digit that is not 5 and replace it with 5.

Perform exactly k operations and return the largest possible resulting number as a string. If s contains fewer than k digits different from 5, return IMPOSSIBLE.

Function

maximumNumberPossible(s: String, k: int) → String

Examples

Example 1

s = "1839559"k = 4return = "5855555"

There are five replaceable digits. To perform exactly four operations while maximizing the result, keep the early digit 8 and replace 1, 3, and the two 9 digits.

Example 2

s = "5567855"k = 4return = "IMPOSSIBLE"

Only three digits are different from 5, so four operations cannot be performed.

Example 3

s = "165232"k = 3return = "565552"

Replace the early digits 1, 2, and 3 with 5. Keeping the digit 6 produces the largest possible result, 565552.

Constraints

  • An integer N in the range [1..100,000] — the length of a string S
  • An integer K in the range [0..100,000]
  • A string S of length N consisting only of digits (0-9), with no leading zeros.
  • Full constraints updated on 05-24-2025 :)
  • More Microsoft problems

    drafts saved locally
    public String maximumNumberPossible(String s, int k) {
      // write your code here
    }
    
    s"1839559"
    k4
    expected"5855555"
    checking account