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"andx = 6, it would be best to insert it between 7 and 3, makingn = "763". - If
n = "-55"andx = 2, it would be best to insert it before the first 5, makingn = "-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
Understanding the Visualization
1
Input
String n and digit x to insert
2
Strategy
Find optimal position based on positive/negative
3
Output
Maximum possible value as string
Key Takeaway
🎯 Key Insight: The optimal position depends on the sign - maximize positive numbers by placing larger digits first, minimize absolute value of negative numbers
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code