Leetcode 397. Integer Replacement
Given a positive integer n
, you can perform the following operations:
n
is even, replace n
with n / 2
.n
is odd, you can replace n
with either n + 1
or n - 1
.Your task is to return the minimum number of replacements needed for n
to become 1.
For example:
n = 8
3
n = 7
4
n = 4
2
n
be very large?
n
can be as large as 2^31 - 1.n
is even, the problem reduces to integerReplacement(n / 2) + 1
.n
is odd, the problem has two subcases:
n
with n + 1
and solve for n + 1
n
with n - 1
and solve for n - 1
Here’s the C++ implementation:
#include <unordered_map>
class Solution {
public:
int integerReplacement(int n) {
return helper(n);
}
private:
std::unordered_map<long long, int> memo;
int helper(long long n) {
if (n == 1) return 0;
if (memo.find(n) != memo.end()) return memo[n];
if (n % 2 == 0) {
memo[n] = 1 + helper(n / 2);
} else {
memo[n] = 1 + std::min(helper(n + 1), helper(n - 1));
}
return memo[n];
}
};
n
is 1, the function returns 0 since no operations are needed.memo
is used to store previously computed results for subproblems.n
: If n
is even, the function recursively solves for n/2
and adds 1 to account for the operation.n
: If n
is odd, it solves both n+1
and n-1
cases recursively, taking the minimum of the two results and adds 1 to account for the operation.This code efficiently computes the minimum number of replacements for any given n
, leveraging memoization to ensure optimal performance.
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?