Difficulty: Easy | Acceptance: 91.30% | Paid: No Topics: Math
You are given two integers, num and t.
An integer x is called achievable if you can perform the following operation exactly t times:
Increment num by 1 and decrement x by 1.
Return the maximum achievable x.
- Examples
- Constraints
- Mathematical Formula
- Iterative Simulation
- Bitwise Operation
Examples
Example 1:
Input: num = 4, t = 1
Output: 6
Explanation: At the end of the operation, num becomes 4 + 1 = 5 and x becomes 6 - 1 = 5. Since num == x, 6 is achievable.
Example 2:
Input: num = 3, t = 2
Output: 7
Explanation: At the end of the operation, num becomes 3 + 2 = 5 and x becomes 7 - 2 = 5. Since num == x, 7 is achievable.
Constraints
0 <= num, t <= 100
Mathematical Formula
Intuition
We need to find an integer x such that after incrementing num by t and decrementing x by t, the values are equal. This leads to the equation num + t = x - t. Solving for x gives x = num + 2t.
Steps
- Calculate
num + 2 * t. - Return the result.
class Solution:
def theMaximumAchievableX(self, num: int, t: int) -> int:
return num + 2 * tComplexity
- Time: O(1)
- Space: O(1)
- Notes: This is the optimal solution with constant time complexity.
Iterative Simulation
Intuition
We can simulate the process described in the problem. In each of the t operations, num increases by 1. To ensure num and x become equal after x is decremented by 1, x must effectively be 2 units larger than num for every operation step.
Steps
- Initialize a loop that runs
ttimes. - In each iteration, add 2 to
num(representing the net difference needed). - Return the final value of
num.
class Solution:
def theMaximumAchievableX(self, num: int, t: int) -> int:
for _ in range(t):
num += 2
return numComplexity
- Time: O(t)
- Space: O(1)
- Notes: While functionally correct for small constraints, the mathematical approach is preferred for O(1) performance.
Bitwise Operation
Intuition
Multiplying an integer by 2 is equivalent to shifting its binary representation left by 1 bit. We can use this bitwise operation to calculate 2 * t.
Steps
- Calculate
num + (t << 1). - Return the result.
class Solution:
def theMaximumAchievableX(self, num: int, t: int) -> int:
return num + (t << 1)Complexity
- Time: O(1)
- Space: O(1)
- Notes: This is an alternative O(1) approach that leverages low-level bit manipulation.