Maximum Value after Insertion — LeetCode 1881 Python Solution
- Problem
- #1881
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
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.
Example
- Input
- n = "99", x = 9
- Output
- "999"
- Explanation
- The result is the same regardless of where you insert 9.
Python solution
class Solution:
def maxValue(self, n: str, x: int) -> str:
i = 0
if n[0] == "-":
i += 1
while i < len(n) and int(n[i]) <= x:
i += 1
else:
while i < len(n) and int(n[i]) >= x:
i += 1
return n[:i] + str(x) + n[i:]Complexity
| Measure | Complexity |
|---|---|
| Time | O(m), where m is the length of n |
| Space | O(1) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 1881. Maximum Value after Insertion is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1881. Maximum Value after Insertion?
- LeetCode 1881. Maximum Value after Insertion is rated Medium on LeetCode.
- What is the time complexity of LeetCode 1881. Maximum Value after Insertion?
- The Python solution on this page runs in O(m), where m is the length of n.
- What is the space complexity of LeetCode 1881. Maximum Value after Insertion?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 1881. Maximum Value after Insertion cover?
- LeetCode 1881. Maximum Value after Insertion is tagged Greedy and String on LeetCode.