Find the Maximum Achievable Number Problem
#2769
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 2769.
Given two integers, num and t. A number x is achievable if it can become equal to num after applying the following operation at most t times:
- Increase or decrease
xby1, and simultaneously increase or decreasenumby1.
Return the maximum possible value of x.
Example 1:
Input: num = 4, t = 1
Output: 6
Explanation:
Apply the following operation once to make the maximum achievable number equal to num:
- Decrease the maximum achievable number by 1, and increase num by 1.
Example 2:
Input: num = 3, t = 2
Output: 7
Explanation:
Apply the following operation twice to make the maximum achievable number equal to num:
- Decrease the maximum achievable number by 1, and increase num by 1.
Constraints:
1 <= num, t <= 50
Solution
Approach: Math
One operation changes x by 1 and num by 1 in the opposite direction, so the gap x - num moves by 2. With at most t operations the gap can be at most 2t, and it is reachable, so the largest achievable x is num + 2t.
Complexity: O(1) time and O(1) space.
class Solution:
def theMaximumAchievableX(self, num: int, t: int) -> int:
return num + t * 2