Skip to main content
Back to problems
#1881
Medium Algorithms

Maximum value after insertion

String Greedy
39.2% acceptance
Feb 25, 2026
401
65
You are given a very large integer n (as a string) and an integer digit x. Maximize n's numerical value by inserting x anywhere in the decimal representation. You cannot insert x to the left of the negative sign.

Solution

Rust
Time O(n)
Space O(1)
LeetCode
solution.rs
impl Solution {
  pub fn max_value(n: String, x: i32) -> String {
    let xc = (b'0' + x as u8) as char;
    let bytes = n.as_bytes();
    let negative = bytes[0] == b'-';
    let start = if negative { 1 } else { 0 };

    let pos = if negative {
      // For negative: insert x where it is LARGER than current digit (to make smaller absolute value)
      (start..bytes.len()).find(|&i| bytes[i] - b'0' > x as u8)
    } else {
      // For positive: insert x where it is LARGER than current digit
      (start..bytes.len()).find(|&i| bytes[i] - b'0' < x as u8)
    };

    let insert_pos = pos.unwrap_or(bytes.len());
    let mut result = n.clone();
    result.insert(insert_pos, xc);
    result
  }
}