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 decreasenum
by1
.
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 asnum
.
Every time you operate:
You can adjust
x
(increase or decrease by 1).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?
If you increase x by 1, you increase num by 1.
If you decrease x by 1, you decrease num by 1.
This means after t
operations:
x
can increase by up to t, andnum
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:
Both
x
andnum
start at the same value.Each operation moves both numbers together by 1.
To maximize
x
, you must use allt
operations to increasex
.
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
Read the inputs:
num
andt
.Use the formula: max_achievable=num+2×t
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:
Each operation increases both
x
andnum
by 1.After
t
operations,x
increases byt
andnum
increases byt
.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