# How to solve a Dynamic Programming Problem ?

Dynamic Programming (DP) is a technique that solves some particular type of problems in Polynomial Time. Dynamic Programming solutions are faster than exponential brute method and can be easily proved for their correctness. Before we study how to think Dynamically for a problem, we need to learn:

```Steps to solve a DP
1) Identify if it is a DP problem
2) Decide a state expression with
least parameters
3) Formulate state relationship
4) Do tabulation (or add memoization)
```

Step 1 : How to classify a problem as a Dynamic Programming Problem?

• Typically, all the problems that require to maximize or minimize certain quantity or counting problems that say to count the arrangements under certain condition or certain probability problems can be solved by using Dynamic Programming.
• All dynamic programming problems satisfy the overlapping subproblems property and most of the classic dynamic problems also satisfy the optimal substructure property. Once, we observe these properties in a given problem, be sure that it can be solved using DP.

Step 2 : Deciding the state
DP problems are all about state and their transition. This is the most basic step which must be done very carefully because the state transition depends on the choice of state definition you make. So, let’s see what do we mean by the term “state”.

State A state can be defined as the set of parameters that can uniquely identify a certain position or standing in the given problem. This set of parameters should be as small as possible to reduce state space.

For example: In our famous Knapsack problem, we define our state by two parameters index and weight i.e DP[index][weight]. Here DP[index][weight] tells us the maximum profit it can make by taking items from range 0 to index having the capacity of sack to be weight. Therefore, here the parameters index and weight together can uniquely identify a subproblem for the knapsack problem.

So, our first step will be deciding a state for the problem after identifying that the problem is a DP problem.
As we know DP is all about using calculated results to formulate the final result.
So, our next step will be to find a relation between previous states to reach the current state.

Step 3 : Formulating a relation among the states
This part is the hardest part of for solving a DP problem and requires a lot of intuition, observation, and practice. Let’s understand it by considering a sample problem

```Given 3 numbers {1, 3, 5}, we need to tell
the total number of ways we can form a number 'N'
using the sum of the given three numbers.
(allowing repetitions and different arrangements).

Total number of ways to form 6 is: 8
1+1+1+1+1+1
1+1+1+3
1+1+3+1
1+3+1+1
3+1+1+1
3+3
1+5
5+1
```

Let’s think dynamically about this problem. So, first of all, we decide a state for the given problem. We will take a parameter n to decide state as it can uniquely identify any subproblem. So, our state dp will look like state(n). Here, state(n) means the total number of arrangements to form n by using {1, 3, 5} as elements.
Now, we need to compute state(n).

How to do it?
So here the intuition comes into action. As we can only use 1, 3 or 5 to form a given number. Let us assume that we know the result for n = 1,2,3,4,5,6 ; being termilogistic let us say we know the result for the
state (n = 1), state (n = 2), state (n = 3) ……… state (n = 6)
Now, we wish to know the result of the state (n = 7). See, we can only add 1, 3 and 5. Now we can get a sum total of 7 by the following 3 ways:

1) Adding 1 to all possible combinations of state (n = 6)
Eg : [ (1+1+1+1+1+1) + 1]
[ (1+1+1+3) + 1]
[ (1+1+3+1) + 1]
[ (1+3+1+1) + 1]
[ (3+1+1+1) + 1]
[ (3+3) + 1]
[ (1+5) + 1]
[ (5+1) + 1]

2) Adding 3 to all possible combinations of state (n = 4);
Eg : [(1+1+1+1) + 3]
[(1+3) + 3]
[(3+1) + 3]

3) Adding 5 to all possible combinations of state(n = 2)
Eg : [ (1+1) + 5]

Now, think carefully and satisfy yourself that the above three cases are covering all possible ways to form a sum total of 7;
Therefore, we can say that result for
state(7) = state (6) + state (4) + state (2)
or
state(7) = state (7-1) + state (7-3) + state (7-5)
In general,
state(n) = state(n-1) + state(n-3) + state(n-5)
So, our code will look like:

## C++

 `// Returns the number of arrangements to ` `// form 'n' ` `int` `solve(``int` `n)` `{ ` `   ``// base case` `   ``if` `(n < 1) ` `      ``return` `0;` `   ``if` `(n == 1)  ` `      ``return` `1;  `   `   ``return` `solve(n-1) + solve(n-3) + solve(n-5);` `}    `

## Python3

 `# Returns the number of arrangements to ` `# form 'n' ` `def` `solve(n):` `  `  `  ``# Base case` `  ``if` `n < ``1``:` `    ``return` `0` `  ``if` `n ``=``=` `1``:` `    ``return` `1` `  `  `  ``return` `(solve(n ``-` `1``) ``+` `          ``solve(n ``-` `3``) ``+` `          ``solve(n ``-` `5``))`   `# This code is contributed by GauriShankarBadola`

The above code seems exponential as it is calculating the same state again and again. So, we just need to add a memoization.

Step 4 : Adding memoization or tabulation for the state
This is the easiest part of a dynamic programming solution. We just need to store the state answer so that next time that state is required, we can directly use it from our memory

Adding memoization to the above code

## C++

 `// initialize to -1` `int` `dp[MAXN];`   `// this function returns the number of ` `// arrangements to form 'n' ` `int` `solve(``int` `n)` `{ ` `  ``// base case` `  ``if` `(n < 1)  ` `      ``return` `0;` `  ``if` `(n == 0)` `      ``return` `1;` `  ``if` `(n == 1)  ` `      ``return` `1;`   `  ``// checking if already calculated` `  ``if` `(dp[n]!=-1) ` `      ``return` `dp[n];`   `  ``// storing the result and returning` `  ``return` `dp[n] = solve(n-1) + solve(n-3) + solve(n-5);` `}`

## Python3

 `# This function returns the number of` `# arrangements to form 'n'`   `# lookup dictionary/hashmap is initialized` `def` `solve(n, lookup ``=` `{}):` `    `  `    ``# Base cases` `    ``# negative number can't be ` `    ``# produced, return 0` `    ``if` `n < ``1``:` `        ``return` `0`   `    ``# 0 can be produced by not ` `    ``# taking any number whereas ` `    ``# 1 can be produced by just taking 1` `    ``if` `n ``=``=` `0` `or` `n ``=``=` `1``:` `        ``return` `1`   `    ``# Checking if number of way for` `    ``# producing n is already calculated ` `    ``# or not if calculated, return that,` `    ``# otherwise calulcate and then return` `    ``if` `n ``not` `in` `lookup:` `        ``lookup[n] ``=` `(solve(n ``-` `1``) ``+` `                     ``solve(n ``-` `3``) ``+` `                     ``solve(n ``-` `5``))` `                     `  `    ``return` `lookup[n]`   `# This code is contributed by GauriShankarBadola`

Another way is to add tabulation and make solution iterative. Please refer tabulation and memoization for more details.
Dynamic Programming comes with a lots of practice. One must try solving various classic DP problems that can be found here

You may check the below problems first and try solving them using the above described steps:-

This article is contributed by Nitish Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up

Article Tags :
Practice Tags :

193

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.
{"ft_lang_label":"__label__en","ft_lang_prob":0.81430197,"math_prob":0.98524815,"size":8624,"snap":"2020-45-2020-50","text_gpt3_token_len":2323,"char_repetition_ratio":0.15150812,"word_repetition_ratio":0.07370518,"special_character_ratio":0.27145177,"punctuation_ratio":0.09008464,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9992329,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-10-24T21:28:23Z\",\"WARC-Record-ID\":\"<urn:uuid:2f3fbe85-8439-44ab-ba97-6e8e1842bf85>\",\"Content-Length\":\"121640\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:22acfaf6-bc48-4a2f-83d5-e8234a4e7d7b>\",\"WARC-Concurrent-To\":\"<urn:uuid:11adfb6a-3fee-40db-b3a5-fac8fbe52c5b>\",\"WARC-IP-Address\":\"23.199.63.65\",\"WARC-Target-URI\":\"https://www.geeksforgeeks.org/solve-dynamic-programming-problem/?ref=lbp\",\"WARC-Payload-Digest\":\"sha1:I5VTT6IMSFYASOQ64XN6LBYXD7PVRZ33\",\"WARC-Block-Digest\":\"sha1:FKHDQC6JPFIGFKF2VFR6DFDNUYYSQVKQ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-45/CC-MAIN-2020-45_segments_1603107884755.46_warc_CC-MAIN-20201024194049-20201024224049-00556.warc.gz\"}"}