Skip to content

1881. Maximum Value after Insertion 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class 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
11
class 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
9
class Solution:
  def maxValue(self, n: str, x: int) -> str:
    isNegative = n[0] == '-'

    for i, c in enumerate(n):
      if not isNegative and ord(c) - ord('0') < x or isNegative and ord(c) - ord('0') > x:
        return n[:i] + str(x) + n[i:]

    return n + str(x)
Back to top