-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathIntegerReplacement.java
More file actions
51 lines (45 loc) · 1.21 KB
/
IntegerReplacement.java
File metadata and controls
51 lines (45 loc) · 1.21 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
44
45
46
47
48
49
50
51
/*https://leetcode.com/problems/integer-replacement/*/
/*Simple DP*/
class Solution {
HashMap<Integer,Integer> dp;
public int integerReplacement(int n) {
dp = new HashMap<Integer,Integer>();
dp.put(0,0);
dp.put(1,0);
recur(n);
//for (int i = 0; i <= n; ++i) System.out.println(dp[i]);
return dp.get(n);
}
public int recur(int n)
{
if (dp.containsKey(n)) return dp.get(n);
if (n == 1) return dp.get(1);
if (n%2 == 0) dp.put(n,recur(n/2)+1);
else dp.put(n,Math.min(recur(n+1),recur(n-1))+1);
return dp.get(n);
}
}
/*Efficient solution*/
class Solution {
public int integerReplacement(int n) {
long val = (long)n;
Deque<Integer> stack = new ArrayDeque<>();
int count = 0;
while(val != 1)
{
if(val % 2 == 0)
{
val = val/2;
count++;
}
else
{
if (val == 3) return count + 2;
else if (((val + 1)/2) % 2 == 0) val++;
else val--;
count++;
}
}
return count;
}
}