Teaching Kids Programming – Minimum Operations to Reduce an Integer to 0 (Greedy Recursion/Top Down Dynamic Programming Algorithm)


Teaching Kids Programming: Videos on Data Structures and Algorithms

You are given a positive integer n, you can do the following operation any number of times:

  • Add or subtract a power of 2 from n.
  • Return the minimum number of operations to make n equal to 0.

A number x is power of 2 if x == 2i where i >= 0.

Example 1:
Input: n = 39
Output: 3
Explanation: We can do the following operations:
– Add 20 = 1 to n, so now n = 40.
– Subtract 23 = 8 from n, so now n = 32.
– Subtract 25 = 32 from n, so now n = 0.
It can be shown that 3 is the minimum number of operations we need to make n equal to 0.

Example 2:
Input: n = 54
Output: 3
Explanation: We can do the following operations:
– Add 21 = 2 to n, so now n = 56.
– Add 23 = 8 to n, so now n = 64.
– Subtract 26 = 64 from n, so now n = 0.
So the minimum number of operations is 3.

Constraints:
1 <= n <= 10^5

Minimum Operations to Reduce an Integer to 0 (Greedy Recursion/Top Down Dynamic Programming Algorithm)

Let f(n) be the minimum number of operations to reduce the non-negative integer n to zero. Then, obviously we have:

tex_178602f269ae43f25eaa5fd6a9e5ebe3 Teaching Kids Programming - Minimum Operations to Reduce an Integer to 0 (Greedy Recursion/Top Down Dynamic Programming Algorithm) algorithms Dynamic Programming greedy algorithm Greedy Algorithm math programming languages Python python Recursion teaching kids programming youtube video
tex_e8870f0268c370cb192af905c0eb7f8c Teaching Kids Programming - Minimum Operations to Reduce an Integer to 0 (Greedy Recursion/Top Down Dynamic Programming Algorithm) algorithms Dynamic Programming greedy algorithm Greedy Algorithm math programming languages Python python Recursion teaching kids programming youtube video where i is non-negative integer i.e. tex_030f26a531f2cde765029701fb07b4e3 Teaching Kids Programming - Minimum Operations to Reduce an Integer to 0 (Greedy Recursion/Top Down Dynamic Programming Algorithm) algorithms Dynamic Programming greedy algorithm Greedy Algorithm math programming languages Python python Recursion teaching kids programming youtube video where x is a power of two.

We can of course, brute force, for any given n, we can try add or subtract any power of two. However, this is not practically feasible as the time complexity will be exponential.

Let’s consider this, let a and b be the closest two power of two, and c and d are also power of two. i.e. c < a < n < b < d where n is not power of two.

We don’t need to consider any other power of two, since the distance between any two power of two will be power of two. For example, a – c is power of two, and so is d – b, so we just have to consider the closest power of twos: a and b. This should give the optimal.

We can find the largest power of two less than n which is represented as tex_7ad9a02d60bedcedcf4e687c8aff0ff6 Teaching Kids Programming - Minimum Operations to Reduce an Integer to 0 (Greedy Recursion/Top Down Dynamic Programming Algorithm) algorithms Dynamic Programming greedy algorithm Greedy Algorithm math programming languages Python python Recursion teaching kids programming youtube video (where i is non-negative integer), and the cost to reduce n to a is tex_db90f071557699184f6e118715e82ade Teaching Kids Programming - Minimum Operations to Reduce an Integer to 0 (Greedy Recursion/Top Down Dynamic Programming Algorithm) algorithms Dynamic Programming greedy algorithm Greedy Algorithm math programming languages Python python Recursion teaching kids programming youtube video , similarly, we can compute the cost to move n to its next power of two, which is tex_750bbd279259b368b3466710ac0e3214 Teaching Kids Programming - Minimum Operations to Reduce an Integer to 0 (Greedy Recursion/Top Down Dynamic Programming Algorithm) algorithms Dynamic Programming greedy algorithm Greedy Algorithm math programming languages Python python Recursion teaching kids programming youtube video .

Then, we just have to choose the smaller cost of these two paths. And from there, there is one more operation to reduce it to zero. We also need to cache the value of f(n) so that it becomes top down dynamic programming algorithm (via memoziation technique).

tex_b9d206eb7d3c20e29888785107b0bc54 Teaching Kids Programming - Minimum Operations to Reduce an Integer to 0 (Greedy Recursion/Top Down Dynamic Programming Algorithm) algorithms Dynamic Programming greedy algorithm Greedy Algorithm math programming languages Python python Recursion teaching kids programming youtube video

We can check if a given integer is power of two by checking its binary form (which should contain only 1 bit set).

1
2
3
4
5
6
7
8
9
10
11
class Solution:
    def minOperations(self, n: int) -> int:
        @cache
        def f(n):
            if n == 0:
                return 0
            if (n & (n - 1)) == 0:
                return 1
            a = int(log2(n))
            b = a + 1
            return min(f(n - (1 << a)), f((1 << b) - n)) + 1
class Solution:
    def minOperations(self, n: int) -> int:
        @cache
        def f(n):
            if n == 0:
                return 0
            if (n & (n - 1)) == 0:
                return 1
            a = int(log2(n))
            b = a + 1
            return min(f(n - (1 << a)), f((1 << b) - n)) + 1

The time complexity is O(LogN) as we are reducing N to LogN every recursive call, and we are caching f(n) values.

Actually, we can perform greedy strategy here, by only choosing the smaller distance, namely, f(min(n – (1 << a), (1 << b) – n)). We want to reduce N as quickly as possible, and even it turns negative, which does not matter as we can add power of two to make it zero.

tex_17a85e32980941a3a4e3fcc3de3cf684 Teaching Kids Programming - Minimum Operations to Reduce an Integer to 0 (Greedy Recursion/Top Down Dynamic Programming Algorithm) algorithms Dynamic Programming greedy algorithm Greedy Algorithm math programming languages Python python Recursion teaching kids programming youtube video

The order of adding or subtracting does not matter.

To see a rigor math proof on this, stay tuned.

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
    def minOperations(self, n: int) -> int:
        @cache
        def f(n):
            if n == 0:
                return 0
            if (n & (n - 1)) == 0:
                return 1
            a = int(log2(n))
            b = a + 1
            n = min(n - (1 << a), (1 << b) - n)
            return f(n) + 1
class Solution:
    def minOperations(self, n: int) -> int:
        @cache
        def f(n):
            if n == 0:
                return 0
            if (n & (n - 1)) == 0:
                return 1
            a = int(log2(n))
            b = a + 1
            n = min(n - (1 << a), (1 << b) - n)
            return f(n) + 1

This reduces the number of calls, and the time/space complexity are also O(LogN).

Minimum Operations to Reduce an Integer to 0

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
1186 words
Last Post: Learn to Manage Your MySQL Database with a Python Script
Next Post: Adding a Short Code Function to Include Any PHP or HTML Files in the WordPress Posts or Pages

The Permanent URL is: Teaching Kids Programming – Minimum Operations to Reduce an Integer to 0 (Greedy Recursion/Top Down Dynamic Programming Algorithm)

Leave a Reply