LeetCode 题解工作台

找出最大的可达成数字

给你两个整数 num 和 t 。如果整数 x 可以在执行下述操作 不超过 t 次的情况下变为与 num 相等,则称其为 可达成数字 : 每次操作将 x 的值增加或减少 1 ,同时可以选择将 num 的值增加或减少 1 。 返回所有可达成数字中的 最大 值 x 。 示例 1: 输入: num = 4,…

category

1

题型

code_blocks

5

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·driven

bolt

答案摘要

我们注意到,每次操作可以将 减少 ,同时将 增加 ,这样 和 的差值就会减少 ,而最多可以操作 次,所以最大可达成数字为 $num + t \times 2$。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·driven 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

给你两个整数 numt 。如果整数 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
lightbulb

解题思路

方法一:数学

我们注意到,每次操作可以将 xx 减少 11,同时将 numnum 增加 11,这样 xxnumnum 的差值就会减少 22,而最多可以操作 tt 次,所以最大可达成数字为 num+t×2num + t \times 2

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def theMaximumAchievableX(self, num: int, t: int) -> int:
        return num + t * 2
speed

复杂度分析

指标
时间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
psychology

面试官常问的追问

外企场景
  • 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.

warning

常见陷阱

外企场景
  • 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.

swap_horiz

进阶变体

外企场景
  • 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.

help

常见问题

外企场景

找出最大的可达成数字题解:数学·driven | LeetCode #2769 简单