1881. Maximum Value after Insertion ¶ Time: $O(n)$ Space: $O(n)$ C++JavaPython 1 2 3 4 5 6 7 8 9 10 11 12class Solution { public: string maxValue(string n, int x) { bool isNegative = n[0] == '-'; for (int i = 0; i < n.length(); ++i) if (!isNegative && n[i] - '0' < x || isNegative && n[i] - '0' > x) return n.substr(0, i) + (char)('0' + x) + n.substr(i); return n + (char)('0' + x); } }; 1 2 3 4 5 6 7 8 9 10 11class Solution { public String maxValue(String n, int x) { boolean isNegative = n.charAt(0) == '-'; for (int i = 0; i < n.length(); ++i) if (!isNegative && n.charAt(i) - '0' < x || isNegative && n.charAt(i) - '0' > x) return n.substring(0, i) + x + n.substring(i); return n + x; } } 1 2 3 4 5 6 7 8 9class Solution: def maxValue(self, n: str, x: int) -> str: isNegative = n[0] == '-' for i, c in enumerate(n): if not isNegative and int(c) < x or isNegative and int(c) > x: return n[:i] + str(x) + n[i:] return n + str(x)