LeetCode 1881: Maximum Value after Insertion Solution

Master LeetCode problem 1881 (Maximum Value after Insertion), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1881. Maximum Value after Insertion

Problem Explanation

Explanation:

To maximize the numerical value of the integer represented by the string n, we need to insert the digit x at the appropriate position in n. The strategy is to iterate through the digits of n and insert x at the first position where x is greater than the current digit if n is positive, or where x is less than the current digit if n is negative. If no such position is found, we insert x at the end of n.

Time Complexity:

The time complexity of this approach is O(n) where n is the length of the string n.

Space Complexity:

The space complexity is O(n) for storing the modified string.


:

Solution Code

class Solution {
    public String maxValue(String n, int x) {
        StringBuilder sb = new StringBuilder();
        
        if (n.charAt(0) == '-') {
            sb.append('-');
            for (int i = 1; i < n.length(); i++) {
                if (n.charAt(i) - '0' > x) {
                    sb.append(x);
                    sb.append(n.substring(i));
                    return sb.toString();
                }
                sb.append(n.charAt(i));
            }
        } else {
            for (char c : n.toCharArray()) {
                if (c - '0' < x) {
                    sb.append(x);
                    sb.append(n.substring(sb.length()));
                    return sb.toString();
                }
                sb.append(c);
            }
        }
        
        sb.append(x);
        return sb.toString();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1881 (Maximum Value after Insertion)?

This page provides optimized solutions for LeetCode problem 1881 (Maximum Value after Insertion) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1881 (Maximum Value after Insertion)?

The time complexity for LeetCode 1881 (Maximum Value after Insertion) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1881 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1881 in Java, C++, or Python.

Back to LeetCode Solutions