Leetcode Problem  2769:  Find the Maximum Achievable Number  (Easy)

Leetcode Problem 2769: Find the Maximum Achievable Number (Easy)

Question :

Given two integers, num and t. A number is achievable if it can become equal to num after applying the following operation:

  • Increase or decrease the number by 1, and simultaneously increase or decrease num by 1.

Return the maximum achievable number after applying the operation at most t times.

Example 1:

  • Input: num = 4, t = 1

  • Output: 6

Example 2:

  • Input: num = 3, t = 2

  • Output: 7

Link to the Question: Click Here

Let’s break this down so it’s easy to understand.


Step 1: Understanding the Problem

Imagine you have two numbers:

  • num starts at a specific value (like 4).

  • x starts at the same value as num.

Every time you operate:

  1. You can adjust x (increase or decrease by 1).

  2. Simultaneously, you must adjust num (increase or decrease by 1 in the same direction).

The goal is to maximize the value of x after using at most t operations.


Breaking it Down: What’s Happening in an Operation?

  1. If you increase x by 1, you increase num by 1.

  2. If you decrease x by 1, you decrease num by 1.

This means after t operations:

  • x can increase by up to t, and

  • num will also increase by the same amount (t).

So, the largest possible value of x is when you use all t operations to increase both x and num.


Step 2: Observations and Formula

Key Observations:

  1. Both x and num start at the same value.

  2. Each operation moves both numbers together by 1.

  3. To maximize x, you must use all t operations to increase x.

After t operations:

  • x increases by t.

  • num also increases by t.

Thus, the maximum achievable value of x becomes:

max_achievable=num+2×t


Steps to Solve

  1. Read the inputs: num and t.

  2. Use the formula: max_achievable=num+2×t

  3. Return the result.


Example Walkthrough

Example 1:

  • Input: num = 4, t = 1

  • Using the formula: max_achievable=num+2×t=4+2×1=6

  • Output: 6

The formula works because:

  1. Each operation increases both x and num by 1.

  2. After t operations, x increases by t and num increases by t.

  3. The total increase to x is the sum of these two effects: t + t = 2 * t.


Step 4: Implementation in Code

Here’s how you can implement the solution in Python:

pythonCopy codedef maxAchievableNumber(num, t):
    return num + 2 * t

# Example usage:
print(maxAchievableNumber(4, 1))  # Output: 6
print(maxAchievableNumber(3, 2))  # Output: 7