Find the Maximum Achievable Number (LeetCode 2769): Solution and Explanation

Easy
Math

An integer x is achievable if at most t operations, each changing both x and num by one, can make them equal. Return the largest achievable x.

Intuition

We want x as large as possible, so x starts above num and has to come down to meet it.

One operation is allowed to move both numbers at once. The best use of it is to pull them toward each other: x goes down by 1 and num goes up by 1. The distance between them drops by 2.

After t operations the distance can drop by at most 2t. So x can start at most 2t above num, and starting exactly there works: after t operations both land on num + t.

Approach: Close the gap from both sides

  1. Compute the largest distance t operations can close: gap = 2 * t.
  2. Return num + gap.

Step-by-step example

num = 4, t = 1
  1. gap = 2 * 1 = 2, so try x = 4 + 2 = 6.
  2. One operation: x goes down to 5 and num goes up to 5. They are equal.
  3. x = 7 would start 3 away, and one operation only closes 2, so 6 is the maximum.

Code: Python, Java, C++

1class Solution:
2    def theMaximumAchievableNumber(self, num: int, t: int) -> int:
3        gap = 2 * t
4        return num + gap
Press play on the visualizer and the running line lights up here.

Time and space complexity

Work as the input growsinput size n →steps
Close the gap from both sides O(1)
Simulate O(t)
Time

O(1)

One multiplication and one addition.

Space

O(1)

No extra memory beyond a single integer.

Other approaches

Simulate (time O(t), space O(1))

Start x at num and add 2 for each of the t operations, or literally move x down and num up t times. Same answer with a loop, useful only to convince yourself.

Common mistakes

  • Returning num + t, which forgets that num also moves toward x in the same operation.
  • Thinking the operation must move both numbers in the same direction. Each one can go up or down independently.

Frequently asked questions

Why is each operation worth 2 and not 1?

Both x and num change in the same operation. Moving them in opposite directions toward each other reduces the distance by 1 from each side, 2 in total.

Does x have to equal the original num?

No. x only has to equal num after the operations, and num moves too. With x = num + 2t they meet at num + t.

What is the smallest achievable x?

By the same argument it is num - 2t: move x up and num down.