-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path397. Integer Replacement.cpp
More file actions
43 lines (37 loc) · 1 KB
/
Copy path397. Integer Replacement.cpp
File metadata and controls
43 lines (37 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/*
Problem Name: Leetcode 397. Integer Replacement
https://leetcode.com/problems/integer-replacement/description/
Company :
*/
/*
Approach 1
Time Complexity : O(logn)
Space Complexity : O(n)
*/
class Solution {
private:
unordered_map<long long, int> memo;
int solve(long long n) {
if (n == 1) return 0;
if (memo.find(n) != memo.end()) return memo[n];
int even = INT_MAX;
int odd_minus = INT_MAX;
int odd_plus = INT_MAX;
if (n % 2 == 0) {
even = 1 + solve(n / 2);
} else {
// Handle the case for n-1 and n+1 without overflow issues
odd_minus = 1 + solve(n - 1);
// Only compute n + 1 if it's within a valid range
if (n < LLONG_MAX) {
odd_plus = 1 + solve(n + 1);
}
}
memo[n] = min(even,min(odd_minus, odd_plus));
return memo[n];
}
public:
int integerReplacement(int n) {
return solve(n);
}
};