- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Suppose we have a number n. Now consider an operation where we can either 1. Decrement n by one 2. If n is even number, then decrement it by n / 2 3. If n is divisible by 3, then decrement by 2 * (n / 3) Finally find the minimum number of operations required to decrement n to zero.

So, if the input is like n = 16, then the output will be 5, as n = 16 even then decreases it by n/2 4 times, it will be 1. Then reduce it by 1 to get 0. So total 5 operations.

To solve this, we will follow these steps −

Define one map dp

Define a function dfs(), this will take x,

ret := x

if x is in dp, then −

return dp[x]

if x <= 0, then −

return x

if x is same as 1, then −

return 1

md2 := x mod 2

md3 := x mod 3

ret := minimum of {ret, md2 + 1 + dfs((x - md2) / 2), md3 + 1 + dfs((x - md3) / 3)}

return dp[x] = ret

From the main method call and return dfs(n)

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; unordered_map <int, int> dp; int dfs(int x){ int ret = x; if(dp.count(x)) return dp[x]; if(x <= 0) return x; if(x == 1) return 1; int md2 = x % 2; int md3 = x % 3; ret = min({ret, md2 + 1 + dfs((x - md2) / 2), md3 + 1 + dfs((x - md3) / 3)}); return dp[x] = ret; } int solve(int n) { return dfs(n); } int main(){ int n = 16; cout << solve(n); }

16

5

- Related Questions & Answers
- Program to find number of operations needed to convert list into non-increasing list in Python
- Find minimum number of Log value needed to calculate Log upto N in C++
- Find minimum operations needed to make an Array beautiful in C++
- Count operations of the given type required to reduce N to 0 in C++
- Program to find minimum operations needed to make two arrays sum equal in Python
- Program to find number of operations required to remove palindromic sublists in C++
- Minimum number of letters needed to make a total of n in C++.
- Program to find number of coins needed to make the changes in Python
- Program to count number of operations needed to make string as concatenation of same string twice in Python
- Find maximum operations to reduce N to 1 in C++
- Program to find minimum number of rocketships needed for rescue in Python
- Program to find number of operations needed to make pairs from first and last side are with same sum in Python
- Program to find minimum number of swaps needed to arrange all pair of socks together in C++
- Program to find maximize score after n operations in Python
- Convert a number m to n using minimum number of given operations in C++

Advertisements