Problem

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.

Examples

Example 1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11

Input: num = 4, t = 1

Output: 6

Explanation:

Apply the following operation once to make the maximum achievable number equal
to `num`:

  * Decrease the maximum achievable number by 1, and increase `num` by 1.

Example 2

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11

Input: num = 3, t = 2

Output: 7

Explanation:

Apply the following operation twice to make the maximum achievable number
equal to `num`:

  * Decrease the maximum achievable number by 1, and increase `num` by 1.

Constraints

  • 1 <= num, t <= 50

Solution

Method 1 – Math Formula

Intuition

Each operation allows us to increase or decrease both the number and num by 1. To maximize the achievable number, we should always increase both as much as possible, so the answer is simply num + 2 * t.

Approach

  1. The maximum achievable number is obtained by increasing both the number and num by 1 in each operation, for a total of t operations.
  2. Thus, the answer is num + 2 * t.

Code

1
2
3
4
5
6
class Solution {
public:
    int theMaximumAchievableX(int num, int t) {
        return num + 2 * t;
    }
};
1
2
3
func theMaximumAchievableX(num int, t int) int {
    return num + 2*t
}
1
2
3
4
5
class Solution {
    public int theMaximumAchievableX(int num, int t) {
        return num + 2 * t;
    }
}
1
2
3
4
5
class Solution {
    fun theMaximumAchievableX(num: Int, t: Int): Int {
        return num + 2 * t
    }
}
1
2
3
class Solution:
    def theMaximumAchievableX(self, num: int, t: int) -> int:
        return num + 2 * t
1
2
3
4
5
impl Solution {
    pub fn the_maximum_achievable_x(num: i32, t: i32) -> i32 {
        num + 2 * t
    }
}
1
2
3
4
5
class Solution {
    theMaximumAchievableX(num: number, t: number): number {
        return num + 2 * t;
    }
}

Complexity

  • ⏰ Time complexity: O(1), just a simple calculation.
  • 🧺 Space complexity: O(1), no extra space used.