# HOW TO BUILD RECURRENCE FOR DYNAMIC PROGRAMMING.

## What is a recurrence?

In dynamic programming, a recurrence is simply an equation that defines itself. It has one or more base cases, also known as non-recursive output, and a recursive case, which is input for which a function, algorithm, or program calls itself.

Because dynamic programming algorithms rely on a recurrence relation involving the optimal solution, the correctness proof will primarily focus on justifying why that recurrence relationship is correct. You can find more information about dynamic programming at algo.monster.

The simplest state of a recurrence relation is when the next term solely depends on the preceding term. If we denote the nth term in the sequence by xn, a recurrence relation of the form xn+1=f(xn) for some function f is obtained. xn+1=2xn/2 is one such example.

Dynamic programming, in general, is an example of a tradeoff between time and space complexity. The recurrence relation would produce an exponential number of subproblems if it did not store the subproblem issues. We can drastically reduce this complexity to polynomial time by sacrificing some space.

## Recurrence illustration.

Consider a function f(n), the definition of which requires you to compute f(1), f(2),…, f(n1) in order to evaluate f(n). Assume that some algorithm for computing f(n) has a time complexity given by the recurrence:

T(n)=n+T(1)+T(2)+…+T(n−1). this  is O(2n).

The values of f(1),f(2),…,f(n – 1) can be stored in an array using dynamic programming, so that computation of f(n) only takes O(n) time if the values of f(1),f(2),…,f(n -1) are already stored in an array.

The total time complexity of such a dynamic programming algorithm would be O(n2), which makes sense when the pseudocode of such an algorithm is considered. But what would be the recurrence? Would it be T(n)=n+max(T(1),…,T(n1)?

## How to build recurrence:

Assume you’ve already solved the problem for all possible inputs  in such a way that i<n

Based on those solutions, try to find the solution for the input n (e.g. f(n)=f(n-1)+f(n-2) ).

Find the base case, inputs for which the problem is simple to solve. For instance, f(0)=1, f(1)=1.

You’ve created a recurring relationship! It is simply connecting the problem to its simpler subproblems.

## First, employ the iterable approach.

It would help if you created the dynamic programming algorithm by storing the subproblem solutions in a table to avoid recomputing them.

This step is straightforward. We have a number and want to use loops to sum its digits. Essentially, we need to know how to count the number’s digits and then add them up one by one.

To make easier iteretability , one method is to cast the variable containing the number to string.

num = 123 #The variable containing the numerical we need to get total of its digits;

num = str(num) # Casting the numerical to a str

s = 0 # Initialize a varible to gather the sum

# Loop over the digits and total them up

for i in range(len(num)):

s += int(num[i])

## Take a look at the parameters of your function.

Using loops to solve the problem will help us understand the solution and figure out all non-recursive aspects. Now that we’ve found the answer, we can dissect it and extract the information we need to proceed.

At this point, we necessitate ask ourselves, “What will the function parameters be if I write this in function form?”

The answer is dependent on the programming language you’re using. We can say that Python only requires one parameter, which is the variable num.

def sumOfDigitsIter(num) :

num = str(num)

s = 0

for i in range(len(num));

s +=int(num[i]

return s

## Subtract a minor problem instance.

We’ll take a closer look at the function parameters once we have them. In our case, there is only one parameter, which is num.

What we require to do now is find the slightest problem instance possible based on the parameters. Remember that our goal was to add the digits of a given number. If the number only has one digit, this problem is simplified.

For example, if num = 3, the answer is the variable itself because there are no more digits to add.

## Add the solution to the simplest possible problem instance.

def sum of Digits Iter(num)

num = str(num)

s = 0

for i in range (len(num)):

s +=int(num[i])

return s

If the parameter num is only a single digit, the loop will still be executed, according to the logic of this function. To avoid this, we can include a conditional statement that runs only if the number of digits in the input number is one.

def Sum Of Digits iter(num):

num = str(num)

if len(num) ==1:

return num

else:

s=0

for i in range(len(num)):

s +=int(num[i])

return s

Recursion occurs at this point. We hadn’t given much thought to recursion until now because we were solving the problem logically. The best way to approach recursion is to start with it, think about it logically, and convert it into a recursive solution.

Let’s take a look at the else section of our function.

else:

s =0

for i in range(len(num)):

s +=int(num[i])

return s

Recursion can be thought of as unrolling a problem instance and then rolling it again. Another way to look at this problem is to say that the total of 123 is 1 + the total of 23, and the sum of 23 is 2 + sum 3 — which is 3.

Rolling this back, the sum is 123 = 1 + 2 + 3 = 6.

Let’s turn that into code. The final section, which deals with one-digit numbers, is already written. What we require to do is convert the remaining num variables to one-digit numbers.

That’s what recursion is.

So I call the same function but with a minor input each time. When I get to the last digit, I’ll have something like 1 + 2 + 3, which will eventually add up to 6.

And there you attain it: a recursive function.

• Another illustration

Consider a different illustration: suppose we want to find the sum of the absolute differences between two lists of integers of equal length. For instance, if we have [15,-4,56,10,-23] and [14,-9,56,14,-23], the answer is 10.

## Step 1: Use loops to solve the problem.

assert len(arr1) == len(arr2)

diff

sum = 0

for i in range(len(arr1)):

diff

sum += abs(arr1[i]-arr2[i])

## Step 2: Get the parameters

parameter list = [arr1, arr2].

## Step 3: Subtract the smallest number of instances

The simplest case of this issue is when both lists are empty; in this case, there is no difference, so the answer is 0.

## Step 4: Resolve the smallest possible instance.

if len(arr1) == 0, then return 0.

You might be wondering why you didn’t make sure that len(arr2) == 0 as well. Because the assert statement already ensured that both lists have the same length, I only need to check the size of one of them to see if they are empty.

## Step 5:Recurse

If I want to accumulate the absolute difference between two lists, I can get the difference between the first two elements, then the second, then the third, and so on, until I finish the elements.

def recDiff(arr1,arr2) :

declare len(arr1) == len (arr2)

If len(arr1) == 0:

return zero

else:

revert abs(arr1-arr2 + recDiff(arr1[1:],arr2[1:])

## Conclusion

Recursion is considered one of the modern techniques that a programmer must learn to become a “good programmer.” However, it can be challenging to grasp at first, and many people struggle to master it.