Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
How to implement minimum step to one using topDown approach using C#?
MinimumStepstoOneTopdownApproach takes integer n and an integer array as input. Parameter n contains the total number of elements. Initial condition checks whether n is equal to 1. If n is equal to 1 then return 0. Initialize op1,op2 and op3 to max value . If n mod 3 is equal to 0 then call MinimumStepstoOneTopdownApproach recursively and assign it to op1 , If n mod 3 is equal to 0 then call MinimumStepstoOneTopdownApproach recursively and assign it to op2 else subtract n by 1 and call MinimumStepstoOneTopdownApproach . Finally call the Math.Min to calculate the minimum of three elements and return the value from the dp array
Time complexity − O(N)
Space complexity − O(N)
Example
public class DynamicProgramming{
public int MinimumStepstoOneTopdownApproach(int n, int[] dp){
if (n == 1){
return 0;
}
int op1, op2, op3;
op1 = int.MaxValue; op2 = int.MaxValue; op3 = int.MaxValue;
if (n % 3 == 0){
op1 = MinimumStepstoOneTopdownApproach(n / 3, dp);
}
if (n % 2 == 0){
op2 = MinimumStepstoOneTopdownApproach(n / 2, dp);
}
op3 = MinimumStepstoOneTopdownApproach(n -1, dp);
int ans = Math.Min(Math.Min(op1, op2), op3)+1;
return dp[n] = ans;
}
}
static void Main(string[] args){
DynamicProgramming dp = new DynamicProgramming();
int[] dpArr = new int[150];
Console.WriteLine(dp.MinimumStepstoOneTopdownApproach(10, dpArr));
}
Output
3
Advertisements