Leetcode 2769. Find the Maximum Achievable Number
You are given two integers num1
and num2
. The task is to return the maximum achievable number by performing a series of operations on num1
. Each operation consists of adding or subtracting num2
from num1
.
num1
and num2
be used?
num1
and num2
are valid inputs.num2
to num1
while it increases the value.The simplest approach, given the constraints, is the following:
#include <iostream>
#include <limits.h>
int maxAchievableNumber(int num1, int num2) {
if (num1 >= 0 && num2 > 0) {
// Infinity in positive direction
return INT_MAX;
} else if (num1 < 0 && num2 > 0) {
// Subtracting num2 makes num1 go negative
return num1;
} else if (num2 == 0) {
// num2 being zero means num1 stays the same
return num1;
} else {
// In case num2 is negative, adding it will decrease the number
// We need to check the direction in which we approach max value
return num1;
}
}
int main() {
int num1 = 10;
int num2 = 2;
std::cout << "Maximum Achievable Number: " << maxAchievableNumber(num1, num2) << std::endl;
return 0;
}
This basic code ensures that the problem is addressed considering most typical operations and constraints within simple integer scenarios.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?