LeetCode 2769: Find the Maximum Achievable Number (Math Derivation)
LeetCode 2769MathGreedyToday we solve LeetCode 2769 - Find the Maximum Achievable Number.
Source: https://leetcode.com/problems/find-the-maximum-achievable-number/
English
Problem Summary
You are given integers num and t. In one move, you can increase or decrease x by 1,
and do the opposite operation on num. After exactly t moves, return the maximum possible x.
Key Insight
In one operation, if x increases by 1 then num decreases by 1 (opposite directions).
To maximize x, we always choose that direction for all t moves. Each move effectively gives a net gain of 2 toward achievable x, so the final answer is num + 2t.
Derivation
Start with target candidate x = num. After one optimal move, x can be pushed one step higher while preserving the allowed relation.
Repeating this for t moves adds 2t total headroom from the original num baseline.
Therefore, x_max = num + 2t.
Complexity Analysis
Time: O(1).
Space: O(1).
Reference Implementations (Java / Go / C++ / Python / JavaScript)
class Solution {
public int theMaximumAchievableX(int num, int t) {
return num + 2 * t;
}
}func theMaximumAchievableX(num int, t int) int {
return num + 2*t
}class Solution {
public:
int theMaximumAchievableX(int num, int t) {
return num + 2 * t;
}
};class Solution:
def theMaximumAchievableX(self, num: int, t: int) -> int:
return num + 2 * tvar theMaximumAchievableX = function(num, t) {
return num + 2 * t;
};中文
题目概述
给定整数 num 和 t。每次操作里,你可以让 x 加 1 或减 1,
同时让 num 做相反操作。恰好做 t 次后,求 x 的最大值。
核心思路
要让 x 最大,每一步都应该让 x 增加 1,而 num 减少 1。
这样做 t 次后,x 一共增加 t,同时由题意关系可化简为最终答案 num + 2t。
推导说明
每一步把 x 往上推 1,总共推 t 次,并与 num 的反向移动配对。
代数化简后最大可达值就是 num + 2t,无需模拟过程。
复杂度分析
时间复杂度:O(1)。
空间复杂度:O(1)。
多语言参考实现(Java / Go / C++ / Python / JavaScript)
class Solution {
public int theMaximumAchievableX(int num, int t) {
return num + 2 * t;
}
}func theMaximumAchievableX(num int, t int) int {
return num + 2*t
}class Solution {
public:
int theMaximumAchievableX(int num, int t) {
return num + 2 * t;
}
};class Solution:
def theMaximumAchievableX(self, num: int, t: int) -> int:
return num + 2 * tvar theMaximumAchievableX = function(num, t) {
return num + 2 * t;
};
Comments