[LeetCode] Maximum Value after Insertion

1881. Maximum Value after Insertion

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.

  • For example, if n = 73 and x = 6, it would be best to insert it between 7 and 3, making n = 763.
  • If n = -55 and x = 2, it would be best to insert it before the first 5, making n = -255.

Return a string representing the maximum value of n​​​​​​ after the insertion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
string findLessValue(string n, int x) {
int pos = n.size();
for(int i = 1; i < n.size(); i++) {
if(n[i] - '0' > x) {pos = i; break; }
}
return n.substr(0,pos) + to_string(x ) + n.substr(pos);
}

string findGreaterValue(string n, int x) {
int pos = n.size();
for(int i = 0; i < n.size(); i++) {
if(n[i] - '0' < x) {pos = i; break; }
}
return n.substr(0,pos) + to_string(x ) + n.substr(pos);
}
public:
string maxValue(string n, int x) {
return n[0] == '-' ? findLessValue(n, x) : findGreaterValue(n, x);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/30/PS/LeetCode/maximum-value-after-insertion/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.