找出最大的可达成数字
难度:
标签:
题目描述
You are given two integers, num
and t
.
An integer x
is called achievable if it can become equal to num
after applying the following operation no more than t
times:
- Increase or decrease
x
by1
, and simultaneously increase or decreasenum
by1
.
Return the maximum possible achievable number. It can be proven that there exists at least one achievable number.
Example 1:
Input: num = 4, t = 1 Output: 6 Explanation: The maximum achievable number is x = 6; it can become equal to num after performing this operation: 1- Decrease x by 1, and increase num by 1. Now, x = 5 and num = 5. It can be proven that there is no achievable number larger than 6.
Example 2:
Input: num = 3, t = 2 Output: 7 Explanation: The maximum achievable number is x = 7; after performing these operations, x will equal num: 1- Decrease x by 1, and increase num by 1. Now, x = 6 and num = 4. 2- Decrease x by 1, and increase num by 1. Now, x = 5 and num = 5. It can be proven that there is no achievable number larger than 7.
Constraints:
1 <= num, t <= 50
代码结果
运行时间: 26 ms, 内存: 16.1 MB
/*
题目思路:
我们需要找出一个数字x,使得我们可以通过对x和num进行不超过t次的操作,使得x变为num,并且x是所有这样的数字中最大的。
操作分为两种:
1. 对x进行+1或-1的操作
2. 对num进行+1或-1的操作
可以推导出最大可达成数字x = num + 2 * t。
因为我们可以让num每次增加1,同时让x减少1,这样每次操作可以增加2的差距,因此t次操作可以增加2t的差距。
*/
import java.util.stream.*;
public class Solution {
public int maxReachableNumber(int num, int t) {
return IntStream.of(num + 2 * t).findFirst().getAsInt();
}
}
解释
方法:
在每次操作中,我们都可以选择增加或减少 x 和 num 的值。要使 x 的值尽可能大,我们应该每次都增加 x 的值,同时减少 num 的值。这样,经过 t 次操作后,x 的最大值将是 num + 2t。
时间复杂度:
O(1)
空间复杂度:
O(1)
代码细节讲解
🦆
为什么在操作中选择增加x的同时减少num,能保证x达到可能的最大值?
▷🦆
如果我们改变策略,选择在每次操作中减少x的值,同时增加num的值,最终x的值将是多少?
▷🦆
题解中的算法是否考虑了所有可能的操作组合,还是只考虑了一种特定的操作策略?
▷🦆
该算法是否总是返回正确的最大可达成数字,还是可能存在误差或特例情况?
▷