LeetCode 题解工作台

插入后的最大值

给你一个非常大的整数 n 和一个整数数字 x ,大整数 n 用一个字符串表示。 n 中每一位数字和数字 x 都处于闭区间 [1, 9] 中,且 n 可能表示一个 负数 。 你打算通过在 n 的十进制表示的任意位置插入 x 来 最大化 n 的 数值 ​​​​​​。但 不能 在负号的左边插入 x 。 例…

category

2

题型

code_blocks

7

代码语言

hub

3

相关题

当前训练重点

中等 · 贪心·invariant

bolt

答案摘要

如果 是负数,那么我们要找到第一个大于 的位置,然后在这个位置插入 ;如果 是正数,那么我们要找到第一个小于 的位置,然后在这个位置插入 。 时间复杂度 ,其中 为 的长度。空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 贪心·invariant 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你一个非常大的整数 n 和一个整数数字 x ,大整数 n 用一个字符串表示。n 中每一位数字和数字 x 都处于闭区间 [1, 9] 中,且 n 可能表示一个 负数

你打算通过在 n 的十进制表示的任意位置插入 x最大化 n数值 ​​​​​​。但 不能 在负号的左边插入 x

  • 例如,如果 n = 73x = 6 ,那么最佳方案是将 6 插入 73 之间,使 n = 763
  • 如果 n = -55x = 2 ,那么最佳方案是将 2 插在第一个 5 之前,使 n = -255

返回插入操作后,用字符串表示的 n 的最大值。

 

示例 1:

输入:n = "99", x = 9
输出:"999"
解释:不管在哪里插入 9 ,结果都是相同的。

示例 2:

输入:n = "-13", x = 2
输出:"-123"
解释:向 n 中插入 x 可以得到 -213、-123 或者 -132 ,三者中最大的是 -123 。

 

提示:

  • 1 <= n.length <= 105
  • 1 <= x <= 9
  • n​​​ 中每一位的数字都在闭区间 [1, 9] 中。
  • n 代表一个有效的整数。
  • n 表示负数时,将会以字符 '-' 开始。
lightbulb

解题思路

方法一:贪心

如果 nn 是负数,那么我们要找到第一个大于 xx 的位置,然后在这个位置插入 xx;如果 nn 是正数,那么我们要找到第一个小于 xx 的位置,然后在这个位置插入 xx

时间复杂度 O(m)O(m),其中 mmnn 的长度。空间复杂度 O(1)O(1)

1
2
3
4
5
6
7
8
9
10
11
12
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:]
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    They mention that n is stored as a string because numeric conversion is unsafe at this size.

  • question_mark

    They hint that the negative case is the same scan shape but with the opposite comparison rule.

  • question_mark

    They care about the first valid insertion point, which is the greedy invariant that makes later positions suboptimal.

warning

常见陷阱

外企场景
  • error

    Using the positive-number rule on negative input and inserting before a smaller digit instead of a larger one.

  • error

    Trying every insertion position and comparing full candidate strings, which is unnecessary and too slow for n.length up to 10^5.

  • error

    Converting n into an integer type, which can overflow and also ignores that this is a string-order greedy problem.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    Return the minimum value after insertion instead of the maximum, which flips the comparison rule for both signs.

  • arrow_right_alt

    Insert a digit into a non-negative decimal string with leading-zero rules, where the insertion condition must respect formatting constraints.

  • arrow_right_alt

    Insert multiple digits from a second string, where the single-step greedy rule becomes a merge-style decision process.

help

常见问题

外企场景

插入后的最大值题解:贪心·invariant | LeetCode #1881 中等