LeetCode 题解工作台
找出最大的可达成数字
给你两个整数 num 和 t 。如果整数 x 可以在执行下述操作 不超过 t 次的情况下变为与 num 相等,则称其为 可达成数字 : 每次操作将 x 的值增加或减少 1 ,同时可以选择将 num 的值增加或减少 1 。 返回所有可达成数字中的 最大 值 x 。 示例 1: 输入: num = 4,…
1
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·driven
答案摘要
我们注意到,每次操作可以将 减少 ,同时将 增加 ,这样 和 的差值就会减少 ,而最多可以操作 次,所以最大可达成数字为 $num + t \times 2$。 时间复杂度 ,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路
题目描述
给你两个整数 num 和 t 。如果整数 x 可以在执行下述操作 不超过 t 次的情况下变为与 num 相等,则称其为 可达成数字 :
- 每次操作将
x的值增加或减少1,同时可以选择将num的值增加或减少1。
返回所有可达成数字中的 最大 值 x。
示例 1:
输入:num = 4, t = 1
输出:6
解释:
执行下述操作可以使最大可达成数字等于 num :
- 最大可达成数字减少 1 ,同时
num增加 1 。
示例 2:
输入:num = 3, t = 2
输出:7
解释:
执行两次下述操作可以使最大可达成数字等于 num :
- 最大可达成数字减少 1 ,同时
num增加 1。
提示:
1 <= num, t <= 50
解题思路
方法一:数学
我们注意到,每次操作可以将 减少 ,同时将 增加 ,这样 和 的差值就会减少 ,而最多可以操作 次,所以最大可达成数字为 。
时间复杂度 ,空间复杂度 。
class Solution:
def theMaximumAchievableX(self, num: int, t: int) -> int:
return num + t * 2
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | complexity is O(1) when using the formula approach, O(t) for simulation. Space complexity is O(1) in all cases since only a few variables are tracked. |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for immediate recognition of the addition pattern in the operation.
- question_mark
Check if candidate correctly computes maximum without redundant iterations.
- question_mark
Verify awareness of constant-time formula versus loop simulation.
常见陷阱
外企场景- error
Overcomplicating with unnecessary loops or conditional checks.
- error
Misunderstanding the operation effect leading to incorrect incremental addition.
- error
Failing to consider the full t operations to reach maximum.
进阶变体
外企场景- arrow_right_alt
Change the operation to multiplication instead of addition, requiring a different formula approach.
- arrow_right_alt
Allow t to vary dynamically based on input conditions.
- arrow_right_alt
Introduce a negative operation, challenging candidate to maximize under alternating operations.