Find the Maximum Achievable Number — Problem & Solution
Find the Maximum Achievable Number solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem.
Find the Maximum Achievable Number is an easy coding problem on math, asked in Amazon and TCS interviews.
- Difficulty: Easy
- Topics: Math
- Asked at: Amazon, TCS
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
An integer x is achievable if, after at most t operations, it can be made equal to num. One operation increases or decreases x by 1 and simultaneously increases or decreases num by 1.
Return the maximum achievable x.
Example 1
Input: num = 4, t = 1
Output: 6
Explanation: Decrease x from 6 to 5 while increasing num from 4 to 5.
Example 2
Input: num = 3, t = 2
Output: 7
Example 3
Input: num = 1, t = 1
Output: 3
Constraints
1 <= num, t <= 50
Hints for Find the Maximum Achievable Number
Hint 1
Each operation can close the gap between
xandnumby 2 — one step from each side.Hint 2
So after
toperations, a gap of at most2tcan be eliminated.Hint 3
The maximum
xis thereforenum + 2t.
How to solve Find the Maximum Achievable Number
Every operation moves x and num by one each, so the gap between them changes by at most 2 per step. Maximising x means starting 2t above num.
Approach
- Note that one operation can reduce
|x - num|by 2 at best. - After
toperations, at most2tof gap can be closed. - Return
num + 2 * t.
Why it works
Starting from x = num + 2t, decreasing x while increasing num each step meets in the middle after exactly t operations. Any larger x leaves a gap that t operations cannot close, since 2 per step is the maximum rate.
Complexity
- Time —
O(1) - Space —
O(1)
Pitfalls
- Answering
num + tforgets thatnummoves too. - The operations must move both values — moving only
xwould halve the reach.
Reference solution
Python
def theMaximumAchievableX(num: int, t: int) -> int:
return num + 2 * tJava
public static int theMaximumAchievableX(int num, int t) {
return num + 2 * t;
}C++
int theMaximumAchievableX(int num, int t) {
return num + 2 * t;
}JavaScript
var theMaximumAchievableX = function(num, t) {
return num + 2 * t;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.