We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Find the Maximum Achievable Number

Number: 2812

Difficulty: Easy

Paid? No

Companies: Amazon, Google


Problem Description

Given two integers, num and t, determine the maximum possible value of a number x such that after applying the following operation at most t times, x can be made equal to num: • In one operation, increase or decrease x by 1 while simultaneously doing the opposite (decrease or increase) to num. Return the maximum possible initial value of x that is achievable.


Key Insights

  • The operation changes both x and num simultaneously, maintaining a predictable difference change.
  • Each operation can change the difference between x and num by exactly 2.
  • To equalize x and num, if the initial difference d = x - num is positive, one can repeatedly decrease x by 1 and increase num by 1 to reduce the difference by 2.
  • Consequently, to make the difference 0, the minimum required moves is d/2, provided d is even.
  • The maximum x we can choose such that d = 2t is x = num + 2t.

Space and Time Complexity

Time Complexity: O(1) – Only a constant number of operations are performed.
Space Complexity: O(1) – Only a fixed amount of extra space is used.


Solution

The key observation is that each allowed operation adjusts the difference between x and num by 2. To achieve equality (final difference 0), if the initial difference d = x - num is positive, you would need to apply the operation "decrease x by 1 and increase num by 1" exactly d/2 times. Since you can perform at most t operations, the maximum valid difference is 2t. Hence, the maximum achievable x is computed as num + 2t.

The solution uses a direct mathematical formula, avoiding loops or extra data structures.


Code Solutions

def maxAchievableNumber(num, t):
    # The maximum achievable initial number x is computed by adding 2*t to num.
    return num + 2 * t

# Example usage:
print(maxAchievableNumber(4, 1))  # Expected output: 6
print(maxAchievableNumber(3, 2))  # Expected output: 7
← Back to All Questions