Maximum Value after Insertion - Problem

You are given a very large integer n, represented as a string, and an integer digit x. The digits in n and the digit x are in the inclusive range [1, 9], and n may represent a negative number.

You want to maximize n's numerical value by inserting x anywhere in the decimal representation of n. You cannot insert x to the left of the negative sign.

Examples:

  • If n = "73" and x = 6, it would be best to insert it between 7 and 3, making n = "763".
  • If n = "-55" and x = 2, it would be best to insert it before the first 5, making n = "-255".

Return a string representing the maximum value of n after the insertion.

Input & Output

Example 1 — Positive Number
$ Input: n = "73", x = 6
Output: "763"
💡 Note: Insert 6 before digit 3 (first digit < 6): 7 → 76 → 763. This gives maximum value 763.
Example 2 — Negative Number
$ Input: n = "-55", x = 2
Output: "-255"
💡 Note: For negative numbers, insert before first digit > x: -5 → -25 → -255. This gives maximum value -255.
Example 3 — Append at End
$ Input: n = "999", x = 5
Output: "9995"
💡 Note: All digits (9) are ≥ 5, so append 5 at the end: 999 → 9995.

Constraints

  • 1 ≤ n.length ≤ 105
  • n consists of only digits, does not have leading zeros, and may have a leading negative sign
  • 1 ≤ x ≤ 9

Visualization

Tap to expand
Maximum Value after Insertion INPUT String n = "73" 7 index 0 3 index 1 Digit to insert: x = 6 6 Input Values n = "73" (positive) x = 6 Goal: Maximize value ALGORITHM STEPS 1 Check Sign n is positive (no "-") 2 Scan Left to Right Find first digit less than x 3 Compare Digits 7 > 6? Yes, continue 3 < 6? Yes, insert here! 4 Insert x at Position Insert 6 before 3 Greedy Comparison i=0: n[0]=7, x=6 7>6 SKIP i=1: n[1]=3, x=6 3<6 INSERT Result: "7" + "6" + "3" = "763" FINAL RESULT Output: "763" 7 6 inserted 3 Value Comparison Original: 73 Result: 763 (OK) MAXIMIZED! Output Value: "763" Key Insight: For POSITIVE numbers: Insert x before the first digit smaller than x (maximize left digits). For NEGATIVE numbers: Insert x before the first digit larger than x (minimize magnitude). Time: O(n) | Space: O(1) - Single pass greedy approach ensures optimal placement. TutorialsPoint - Maximum Value after Insertion | Greedy Single Pass Approach
Asked in
Google 15 Amazon 12 Microsoft 8 Facebook 6
23.5K Views
Medium Frequency
~15 min Avg. Time
847 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen