Minimize steps to reach K from 0 by adding 1 or doubling at each step
Given a positive integer K, the task is to find the minimum number of operations of the following two types, required to change 0 to K:
- Add one to the operand
- Multiply the operand by 2.
Input: K = 1
Step 1: 0 + 1 = 1 = K
Input: K = 4
Step 1: 0 + 1 = 1,
Step 2: 1 * 2 = 2,
Step 3: 2 * 2 = 4 = K
- If K is an odd number, the last step must be adding 1 to it.
- If K is an even number, the last step is to multiply by 2 to minimize the number of steps.
- Create a dp table that stores in every dp[i], the minimum steps required to reach i.
- Let us consider an even number X
- Now we have two options:
- Now if we choose X-1:
-> X-1 is an odd number , since X is even
-> Hence we choose subtract 1 operation and we have X-2
->Now we have X-2, which is also an even number , Now again we have two options either to subtract 1 or to divide by 2
->Now let us choose divide by 2 operation , hence we have ( X – 2 )/2 => (X/2) -1
- Now if we choose X/2:
-> We can do the subtract 1 operation to reach (X/2)-1
- Now let us consider sequence of both the cases:
When we choose X-1 : X -> X-1 -> X-2 -> (X/2)-1 [ totally three operations ]
When we choose X/2 : X -> X/2 -> (X/2)-1 [ totally two operations ]
- Hence we can say that for a given even number , choosing the divide by 2 operation will always give us the minimum number of steps
- Hence proved
Below is the implementation of the above approach:
Time Complexity: O(k)
Auxiliary Space: O(k)